Este trabajo consiste en desarrollar ejercicios del libro guía de la materia Técnicas de aprendizaje estadístico, A Introduction to Statistical Learning with Application in R[2]. El listado de ejercicios por sección son:
Sección 4.7 - Aplicación
10. This question should be answered using the Weekly data set, which is part of the ISLR package. This data is similar in nature to the Smarket data from this chapter’s lab, except that it contains 1,089 weekly returns for 21 years, from the beginning of 1990 to the end of 2010.
El dataset Weekly contiene año a año información del rendimiento semanal para el índice bursátil S&P 500, las dimensiones con las que cuenta el dataset son:
Indicador si el mercado tuvo retornos positivos o negativos en determinada semana (Direction)
a. Produce some numerical and graphical summaries of the Weekly data. Do there appear to be any patterns?
Estádisticos básicos del data set Weekly
## Year Lag1 Lag2 Lag3
## Min. :1990 Min. :-18.1950 Min. :-18.1950 Min. :-18.1950
## 1st Qu.:1995 1st Qu.: -1.1540 1st Qu.: -1.1540 1st Qu.: -1.1580
## Median :2000 Median : 0.2410 Median : 0.2410 Median : 0.2410
## Mean :2000 Mean : 0.1506 Mean : 0.1511 Mean : 0.1472
## 3rd Qu.:2005 3rd Qu.: 1.4050 3rd Qu.: 1.4090 3rd Qu.: 1.4090
## Max. :2010 Max. : 12.0260 Max. : 12.0260 Max. : 12.0260
## Lag4 Lag5 Volume
## Min. :-18.1950 Min. :-18.1950 Min. :0.08747
## 1st Qu.: -1.1580 1st Qu.: -1.1660 1st Qu.:0.33202
## Median : 0.2380 Median : 0.2340 Median :1.00268
## Mean : 0.1458 Mean : 0.1399 Mean :1.57462
## 3rd Qu.: 1.4090 3rd Qu.: 1.4050 3rd Qu.:2.05373
## Max. : 12.0260 Max. : 12.0260 Max. :9.32821
## Today Direction
## Min. :-18.1950 Down:484
## 1st Qu.: -1.1540 Up :605
## Median : 0.2410
## Mean : 0.1499
## 3rd Qu.: 1.4050
## Max. : 12.0260
De los estadísticos básicos se tiene que los porcentajes de retorno en los diferentes períodos del tiempo son muy similares en su distribución, como bien se puede corroborar en la siguiente gráfica.
Por su parte, la variable objetivo, Direction, es binaria, toma los valores de down y up. El volumen de acciones negociadas en promedio son de 1.6 miles de millones.
A medida que pasan los añs, los volumen de acciones negociadas en miles de millones tienen mayor rango de oscilación.
La única variable que parece explicar la variable objetivo Direction es Today, de resto, la variable objetivo, no es explicada por ninguna de las demás variables predictoras.
No hay valores faltantes en el dataset.
b. Use the full data set to perform a logistic regression with Direction as the response and the five lag variables plus Volume as predictors. Use the summary function to print the results. Do any of the predictors appear to be statistically significant? If so, which ones?
Entrenando la regresión logística
##
## Call:
## glm(formula = Direction ~ Lag1 + Lag2 + Lag3 + Lag4 + Lag5 +
## Volume, family = binomial, data = Weekly)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.6949 -1.2565 0.9913 1.0849 1.4579
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 0.26686 0.08593 3.106 0.0019 **
## Lag1 -0.04127 0.02641 -1.563 0.1181
## Lag2 0.05844 0.02686 2.175 0.0296 *
## Lag3 -0.01606 0.02666 -0.602 0.5469
## Lag4 -0.02779 0.02646 -1.050 0.2937
## Lag5 -0.01447 0.02638 -0.549 0.5833
## Volume -0.02274 0.03690 -0.616 0.5377
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 1496.2 on 1088 degrees of freedom
## Residual deviance: 1486.4 on 1082 degrees of freedom
## AIC: 1500.4
##
## Number of Fisher Scoring iterations: 4
y analizando sus resultados, el p-value es menor que 0.05 para el coeficiente de lag2, esta variable es estadísticamente significativa con la variable dependiente.
c. Compute the confusion matrix and overall fraction of correct predictions. Explain what the confusion matrix is telling you about the types of mistakes made by logistic regression.
## Up
## Down 0
## Up 1
La división de los datos de entrenamiento y prueba para predecir el modelo es un 75%-25%
En total se tienen 817, 10 datos para entrenamiento
En total se tienen 272, 10 datos para prueba
Se entrena la regresión logística con los datos de entrenamiento
##
## Call:
## glm(formula = Direction_factor ~ Lag1 + Lag2 + Lag3 + Lag4 +
## Lag5 + Volume, family = binomial, data = training_wee)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.497 -1.257 1.004 1.081 1.429
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 0.281762 0.099377 2.835 0.00458 **
## Lag1 -0.045039 0.030619 -1.471 0.14131
## Lag2 0.047725 0.033242 1.436 0.15110
## Lag3 -0.002579 0.032122 -0.080 0.93602
## Lag4 -0.028363 0.031347 -0.905 0.36557
## Lag5 -0.003701 0.030545 -0.121 0.90356
## Volume -0.035191 0.043215 -0.814 0.41546
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 1122.4 on 816 degrees of freedom
## Residual deviance: 1116.7 on 810 degrees of freedom
## AIC: 1130.7
##
## Number of Fisher Scoring iterations: 4
Al entrenar el modelo con los datos de entrenamiento, no se encuentra ninguna características estadisticamente significativa.
Se predice la regresión logística con los datos de prueba
## Down Up
## 0.5463548 0.5570822
Para ambos clases, se predice una probabilidad promedio del 55%, lo cual es una probabilidad alta.
## Confusion Matrix and Statistics
##
## Real
## Predicho Down Up
## Down 15 11
## Up 106 140
##
## Accuracy : 0.5699
## 95% CI : (0.5087, 0.6295)
## No Information Rate : 0.5551
## P-Value [Acc > NIR] : 0.3354
##
## Kappa : 0.0554
##
## Mcnemar's Test P-Value : <2e-16
##
## Sensitivity : 0.12397
## Specificity : 0.92715
## Pos Pred Value : 0.57692
## Neg Pred Value : 0.56911
## Prevalence : 0.44485
## Detection Rate : 0.05515
## Detection Prevalence : 0.09559
## Balanced Accuracy : 0.52556
##
## 'Positive' Class : Down
##
De la matriz de confusión se concluye que la regresión logística tiene un accuracy del 56%, este indicador nos dice que tan bueno es el modelo prediciendo ambas clases Down y Up, un 56% es un porcentaje no muy bueno, por lo cual se podría concluir que el clasificador por regresión logística no es el mejor. Por su parte la especificiada es alta, 92%, esta nos indica que para la clase up de un total de 151 registros pertenecientes a esta clase, el modelo fue capaz de predecir 140.
d. Now fit the logistic regression model using a training data period from 1990 to 2008, with Lag2 as the only predictor. Compute the confusion matrix and the overall fraction of correct predictions for the held out data (that is, the data from 2009 and 2010).
Se particionan nuevamente los datos y se obtienen
## [1] "Cantidad de datos para entrenamiento 985"
## [1] "Cantidad de datos para prueba 104"
Se entrena la regresión logística
##
## Call:
## glm(formula = Direction_factor ~ Lag2, family = binomial, data = trainingd)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.536 -1.264 1.021 1.091 1.368
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 0.20326 0.06428 3.162 0.00157 **
## Lag2 0.05810 0.02870 2.024 0.04298 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 1354.7 on 984 degrees of freedom
## Residual deviance: 1350.5 on 983 degrees of freedom
## AIC: 1354.5
##
## Number of Fisher Scoring iterations: 4
El modelo teniendo en cuenta una variable sola variable predictora, Lag2, indica que ella es estadísticamente significativa
A partir de la matriz de confusión
## Confusion Matrix and Statistics
##
##
## weekly_rep_d Down Up
## Down 9 5
## Up 34 56
##
## Accuracy : 0.625
## 95% CI : (0.5247, 0.718)
## No Information Rate : 0.5865
## P-Value [Acc > NIR] : 0.2439
##
## Kappa : 0.1414
##
## Mcnemar's Test P-Value : 7.34e-06
##
## Sensitivity : 0.20930
## Specificity : 0.91803
## Pos Pred Value : 0.64286
## Neg Pred Value : 0.62222
## Prevalence : 0.41346
## Detection Rate : 0.08654
## Detection Prevalence : 0.13462
## Balanced Accuracy : 0.56367
##
## 'Positive' Class : Down
##
En este ejercicio el poder predictivo disminuye, si bien la distribución del data set difiere y este cambio influye en la forma predecir del modelo, también se disminuyeron considerablemente las variables predictoras, dejando únicamente Lag2. Dado los valores arrojados por sensibilidad y especificidad se concluye que lag2 para la regresión logística aporta más prediciendo para la clase Up que la Down.
e. Repeat (d) using LDA - Análisis Discriminante Lineal
Entrenamiento del modelo LDA
## Call:
## lda(Direction_factor ~ Lag2, data = trainingd)
##
## Prior probabilities of groups:
## Down Up
## 0.4477157 0.5522843
##
## Group means:
## Lag2
## Down -0.03568254
## Up 0.26036581
##
## Coefficients of linear discriminants:
## LD1
## Lag2 0.4414162
Según la función discriminante de LDA, la probabilidad posterior de que el mercado tenga un retorno positivo en determinada semana es del 55% frente a un 44% de que sea negativo.
De la matriz de confusión
## Confusion Matrix and Statistics
##
## Clase predicha
## Clase real Down Up
## Down 9 34
## Up 5 56
##
## Accuracy : 0.625
## 95% CI : (0.5247, 0.718)
## No Information Rate : 0.8654
## P-Value [Acc > NIR] : 1
##
## Kappa : 0.1414
##
## Mcnemar's Test P-Value : 7.34e-06
##
## Sensitivity : 0.64286
## Specificity : 0.62222
## Pos Pred Value : 0.20930
## Neg Pred Value : 0.91803
## Prevalence : 0.13462
## Detection Rate : 0.08654
## Detection Prevalence : 0.41346
## Balanced Accuracy : 0.63254
##
## 'Positive' Class : Down
##
Con LDA los resultados comparados con la regresión logística no difiere considerablemente, esto puede ser debido a que estamos trabajando un problema de clasificación en dos niveles. Sin embargo para LDA los indicadores disminuyen un poco.
f.Repeat (d) using QDA - Análisis Discriminante Cuadrático
Entrenamiento de QDA
## Call:
## qda(Direction_factor ~ Lag2, data = trainingd)
##
## Prior probabilities of groups:
## Down Up
## 0.4477157 0.5522843
##
## Group means:
## Lag2
## Down -0.03568254
## Up 0.26036581
El resultado en cuento a probabilidades es muy similar al arrojado por LDA a nivel de probabiliades.
## Confusion Matrix and Statistics
##
## Clase predicha
## Clase real Down Up
## Down 0 43
## Up 0 61
##
## Accuracy : 0.5865
## 95% CI : (0.4858, 0.6823)
## No Information Rate : 1
## P-Value [Acc > NIR] : 1
##
## Kappa : 0
##
## Mcnemar's Test P-Value : 1.504e-10
##
## Sensitivity : NA
## Specificity : 0.5865
## Pos Pred Value : NA
## Neg Pred Value : NA
## Prevalence : 0.0000
## Detection Rate : 0.0000
## Detection Prevalence : 0.4135
## Balanced Accuracy : NA
##
## 'Positive' Class : Down
##
Sin embargo este acercamiento en la predicción no aporta en la casificación de la clase Down por lo cual el valor de la sensibilidad no aplica.
g. Repeat (d) using KNN with K = 1.
Entrenamiento de los k vecinos más cercanos
## Confusion Matrix and Statistics
##
##
## weekly_knn Down Up
## Down 37 15
## Up 6 46
##
## Accuracy : 0.7981
## 95% CI : (0.7081, 0.8704)
## No Information Rate : 0.5865
## P-Value [Acc > NIR] : 4.031e-06
##
## Kappa : 0.5962
##
## Mcnemar's Test P-Value : 0.08086
##
## Sensitivity : 0.8605
## Specificity : 0.7541
## Pos Pred Value : 0.7115
## Neg Pred Value : 0.8846
## Prevalence : 0.4135
## Detection Rate : 0.3558
## Detection Prevalence : 0.5000
## Balanced Accuracy : 0.8073
##
## 'Positive' Class : Down
##
Este acercamiento con vecimos más cercanos da mejores rendimientos para ambas clases con un sólo vecino cercano.
h. Which of these methods appears to provide the best results on this data?
El método que parece mejorar los resultados a partir del set de datos de Weekly es vecinos más cercanos, donde con un sólo vecino, puede clasificar correctamente ambas clases. El accuracy del modelo es del 79%, lo cual es aceptable, pero cuando se revisa la sensibilidad, en este caso la porció de clase Up clasificada como Up, se tiene que es del 86% y las clases positivas, Down, por su parte del 75%.
i. Experiment with different combinations of predictors, includ-ing possible transformations and interactions, for each of the methods. Report the variables, method, and associated confusion matrix that appears to provide the best results on the held out data. Note that you should also experiment with values for K in the KNN classifier.
Se procede a variar el valor de k en vecinos más cercanos, método que parece más apropiado, para revisar como esta variación afecta los resultados anteriores
## Confusion Matrix and Statistics
##
##
## weekly_knn Down Up
## Down 37 15
## Up 6 46
##
## Accuracy : 0.7981
## 95% CI : (0.7081, 0.8704)
## No Information Rate : 0.5865
## P-Value [Acc > NIR] : 4.031e-06
##
## Kappa : 0.5962
##
## Mcnemar's Test P-Value : 0.08086
##
## Sensitivity : 0.8605
## Specificity : 0.7541
## Pos Pred Value : 0.7115
## Neg Pred Value : 0.8846
## Prevalence : 0.4135
## Detection Rate : 0.3558
## Detection Prevalence : 0.5000
## Balanced Accuracy : 0.8073
##
## 'Positive' Class : Down
##
Probando con los valores de k = 3 y k = 5, se obtienen los mismos comportamientos que con k = 1.
11. In this problem, you will develop a model to predict whether a given car gets high or low gas mileage based on the Auto data set.
El dataset Auto, contiene información del rendimiento de la gasolina, los caballos de fuerza de 392 vehículos. Las dimensiones con las que se cuentan en el dataset son:
name: nombre del vehículo
a. Create a binary variable, mpg01, that contains a 1 if mpg contains a value above its median, and a 0 if mpg contains a value below its median. You can compute the median using the median() function. Note you may find it helpful to use the data.frame() function to create a single data set containing both mpg01 and the other Auto variables.
auto_df <- Auto
mpg_median <- median(auto_df$mpg)
auto_df$mpg01 <- ifelse(auto_df$mpg >= mpg_median, 1, 0)
b. Explore the data graphically in order to investigate the association between mpg01 and the other features. Which of the other features seem most likely to be useful in predicting mpg01? Scatterplots and boxplots may be useful tools to answer this question. Describe your findings.
Parece existir una relación lineal entre los caballos de fuerza con el peso y la aceleración.
De las demás características, las que menos hacen separación de los datos son name y origin
c. Split the data into a training set and a test set.
## [1] "Total de datos usados para entrenamiento 294"
## [1] "Total de datos usados para prueba 98"
d. Perform LDA on the training data in order to predict mpg01 using the variables that seemed most associated with mpg01 in (b). What is the test error of the model obtained?
Entrenamiento de LDA
## Call:
## lda(mpg01 ~ mpg + cylinders + displacement + horsepower + weight +
## acceleration + year, data = training_auto)
##
## Prior probabilities of groups:
## 0 1
## 0.5 0.5
##
## Group means:
## mpg cylinders displacement horsepower weight acceleration
## 0 16.83129 6.809524 275.4830 131.25170 3625.014 14.42517
## 1 30.20000 4.204082 117.1054 78.65986 2343.565 16.67415
## year
## 0 74.38776
## 1 77.61224
##
## Coefficients of linear discriminants:
## LD1
## mpg 2.017944e-01
## cylinders -4.266285e-01
## displacement -1.014899e-03
## horsepower 1.129859e-02
## weight 1.039066e-05
## acceleration 2.499751e-02
## year -2.211208e-02
Según la función discriminante de LDA, la probabilidad posterior que los valores de las millas por galón sea mayor que la media es del 50%.
De la matriz de confusión
## Confusion Matrix and Statistics
##
## Clase predicha
## Clase real 0 1
## 0 44 5
## 1 1 48
##
## Accuracy : 0.9388
## 95% CI : (0.8715, 0.9772)
## No Information Rate : 0.5408
## P-Value [Acc > NIR] : <2e-16
##
## Kappa : 0.8776
##
## Mcnemar's Test P-Value : 0.2207
##
## Sensitivity : 0.9778
## Specificity : 0.9057
## Pos Pred Value : 0.8980
## Neg Pred Value : 0.9796
## Prevalence : 0.4592
## Detection Rate : 0.4490
## Detection Prevalence : 0.5000
## Balanced Accuracy : 0.9417
##
## 'Positive' Class : 0
##
## [1] "Error de prueba 6.12244897959184 %"
Este clasificador a la hora de predecir es óptimo, tiene una accuracy del 93% y ambas clases las clasifica en más del 90%. El error en las pruebas es bajo, solo el 6%
e. Perform QDA on the training data in order to predict mpg01 using the variables that seemed most associated with mpg01 in (b). What is the test error of the model obtained?
Entrenamiento con QDA
## Call:
## qda(mpg01 ~ mpg + cylinders + displacement + horsepower + weight +
## acceleration + year, data = training_auto)
##
## Prior probabilities of groups:
## 0 1
## 0.5 0.5
##
## Group means:
## mpg cylinders displacement horsepower weight acceleration
## 0 16.83129 6.809524 275.4830 131.25170 3625.014 14.42517
## 1 30.20000 4.204082 117.1054 78.65986 2343.565 16.67415
## year
## 0 74.38776
## 1 77.61224
El resultado en cuento a probabilidades es muy similar al arrojado por LDA a nivel de probabiliades.
De la matriz de confusión
## Confusion Matrix and Statistics
##
## Clase predicha
## Clase real 0 1
## 0 45 4
## 1 1 48
##
## Accuracy : 0.949
## 95% CI : (0.8849, 0.9832)
## No Information Rate : 0.5306
## P-Value [Acc > NIR] : <2e-16
##
## Kappa : 0.898
##
## Mcnemar's Test P-Value : 0.3711
##
## Sensitivity : 0.9783
## Specificity : 0.9231
## Pos Pred Value : 0.9184
## Neg Pred Value : 0.9796
## Prevalence : 0.4694
## Detection Rate : 0.4592
## Detection Prevalence : 0.5000
## Balanced Accuracy : 0.9507
##
## 'Positive' Class : 0
##
## [1] "Error de prueba 5.10204081632653 %"
Con QDA se mejoran las métricas de clasificiación del modelo y el error de predicción disminuye a un 5%.
f. Perform logistic regression on the training data in order to predict mpg01 using the variables that seemed most associated with mpg01 in (b). What is the test error of the model obtained?
Entrenamiento de regresión logística
##
## Call:
## glm(formula = mpg01 ~ mpg + cylinders + displacement + horsepower +
## weight + acceleration + year, family = binomial, data = training_auto)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.606e-04 -2.100e-08 0.000e+00 2.100e-08 1.721e-04
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -9.269e+02 4.485e+05 -0.002 0.998
## mpg 4.486e+01 7.723e+03 0.006 0.995
## cylinders -7.186e+00 1.802e+04 0.000 1.000
## displacement -2.203e-02 4.908e+02 0.000 1.000
## horsepower 1.482e+00 6.325e+03 0.000 1.000
## weight -1.148e-02 1.866e+02 0.000 1.000
## acceleration 4.966e+00 1.762e+04 0.000 1.000
## year -3.096e+00 4.024e+03 -0.001 0.999
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 4.0757e+02 on 293 degrees of freedom
## Residual deviance: 1.3164e-07 on 286 degrees of freedom
## AIC: 16
##
## Number of Fisher Scoring iterations: 25
Ninguna de las variables seleccionadas para la predición parecen ser estadísticamente significativas.
De la matriz de confusión
## Confusion Matrix and Statistics
##
##
## auto_predict_log 0 1
## 0 49 0
## 1 0 49
##
## Accuracy : 1
## 95% CI : (0.9631, 1)
## No Information Rate : 0.5
## P-Value [Acc > NIR] : < 2.2e-16
##
## Kappa : 1
##
## Mcnemar's Test P-Value : NA
##
## Sensitivity : 1.0
## Specificity : 1.0
## Pos Pred Value : 1.0
## Neg Pred Value : 1.0
## Prevalence : 0.5
## Detection Rate : 0.5
## Detection Prevalence : 0.5
## Balanced Accuracy : 1.0
##
## 'Positive' Class : 0
##
## [1] "Error de prueba 0 %"
De acuerdo a los resultados obtenidos parece ser que la regresió logística esta sobreajustada, dando un accuracy del 100%.
g. Perform KNN on the training data, with several values of K, in order to predict mpg01. Use only the variables that seemed most associated with mpg01 in (b). What test errors do you obtain? Which value of K seems to perform the best on this data set?
Entrenamiento KNN
## Confusion Matrix and Statistics
##
##
## auto_knn_predic 0 1
## 0 45 2
## 1 4 47
##
## Accuracy : 0.9388
## 95% CI : (0.8715, 0.9772)
## No Information Rate : 0.5
## P-Value [Acc > NIR] : <2e-16
##
## Kappa : 0.8776
##
## Mcnemar's Test P-Value : 0.6831
##
## Sensitivity : 0.9184
## Specificity : 0.9592
## Pos Pred Value : 0.9574
## Neg Pred Value : 0.9216
## Prevalence : 0.5000
## Detection Rate : 0.4592
## Detection Prevalence : 0.4796
## Balanced Accuracy : 0.9388
##
## 'Positive' Class : 0
##
Se prueba con k = [1,2,3,4,5,6,7] y se muestran los resultados con k=2, ya que es el k que da mejores resultados, con un accuracy del 93% y una alta tasa de efectividad en ambas clases.
## [1] "Error de prueba 6.12244897959184 %"
En el desarrollo de los ejercicios anteriores para el dataset Auto, todos los clasificadores tienen unas buenas métricas y bajo error.
12. This problem involves writing functions.
a. Write a function, Power(), that prints out the result of raising 2 to the 3rd power. In other words, your function should compute 23 and print out the results. Hint: Recall that x^a raises x to the power a. Use the print() function to output the result.
Power <- function(x) {
print( 2 ^ x)
}
b. Create a new function, Power2(), that allows you to pass any two numbers, x and a, and prints out the value of x^a. You can do this by beginning your function with the line Power2=function(x,a){ You should be able to call your function by entering, for instance, Power2(3,8) on the command line. This should output the value of 38, namely, 6, 561.
Power2 <- function(x,y) {
print( x ^ y )
}
c. Using the Power2() function that you just wrote, compute 103, 817, and 1313.
## [1] 1000
## [1] 2.2518e+15
## [1] 2248091
d. Now create a new function, Power3(), that actually returns the result x^a as an R object, rather than simply printing it to the screen. That is, if you store the value x^a in an object called result within your function, then you can simply return() this result, using the following line: return() return(result) The line above should be the last line in your function, before the } symbol.
Power3 <- function(x,y) {
result <- x ^ y
return(result)
}
e. Now using the Power3() function, create a plot of f(x) = x2. The x-axis should display a range of integers from 1 to 10, and the y-axis should display x2. Label the axes appropriately, and use an appropriate title for the figure. Consider displaying either the x-axis, the y-axis, or both on the log-scale. You can do this by using log=‘‘x’’, log=‘‘y’’, or log=‘‘xy’’ as arguments to the plot() function.
f. Create a function, PlotPower(), that allows you to create a plot of x against x^a for a fixed a and for a range of values of x. For instance, if you call PlotPower (1:10 ,3) then a plot should be created with an x-axis taking on values 1,2,…,10, and a y-axis taking on values 13,23,…,103.
PlotPower <- function(x,a){
plot(x, Power3(x,a), main = paste(' Potencias - f(x) = x^',a), xlab = 'x', ylab = paste('x^',a))
}
13. Using the Boston data set, fit classification models in order to predict whether a given suburb has a crime rate above or below the median. Explore logistic regression, LDA, and KNN models using various subsets of the predictors. Describe your findings.
Boston dataset que tiene información del valor de las casas en los suburbios de Boston. Posee variables como:
Se dividen los datos en prueba y entrenamiento
## [1] "Total de datos usados para entrenamiento 380"
## [1] "Total de datos usados para prueba 126"
Regresión logística
##
## Call:
## glm(formula = crim_class ~ ., family = binomial, data = training_boston)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.347e-03 -2.000e-08 0.000e+00 2.000e-08 2.505e-03
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -6.585e+02 2.664e+05 -0.002 0.998
## crim 8.995e+02 2.984e+04 0.030 0.976
## zn 1.804e+00 7.671e+02 0.002 0.998
## indus -6.480e+00 1.754e+03 -0.004 0.997
## chas -7.217e+00 3.054e+04 0.000 1.000
## nox 3.231e+02 1.858e+05 0.002 0.999
## rm -4.010e+00 1.298e+04 0.000 1.000
## age 3.514e-01 2.201e+02 0.002 0.999
## dis -1.564e+01 5.426e+03 -0.003 0.998
## rad 6.591e+00 5.290e+03 0.001 0.999
## tax -5.736e-01 2.467e+02 -0.002 0.998
## ptratio 2.045e+01 7.236e+03 0.003 0.998
## black 2.964e-01 7.570e+02 0.000 1.000
## lstat 2.163e+00 7.374e+02 0.003 0.998
## medv -4.834e-01 1.304e+03 0.000 1.000
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 5.2679e+02 on 379 degrees of freedom
## Residual deviance: 2.0064e-05 on 365 degrees of freedom
## AIC: 30
##
## Number of Fisher Scoring iterations: 25
Ninguna de las variables seleccionadas para la predición parecen ser estadísticamente significativas.
De la matriz de confusión
## Confusion Matrix and Statistics
##
##
## boston_predict_log 0 1
## 0 62 4
## 1 1 59
##
## Accuracy : 0.9603
## 95% CI : (0.9098, 0.987)
## No Information Rate : 0.5
## P-Value [Acc > NIR] : <2e-16
##
## Kappa : 0.9206
##
## Mcnemar's Test P-Value : 0.3711
##
## Sensitivity : 0.9841
## Specificity : 0.9365
## Pos Pred Value : 0.9394
## Neg Pred Value : 0.9833
## Prevalence : 0.5000
## Detection Rate : 0.4921
## Detection Prevalence : 0.5238
## Balanced Accuracy : 0.9603
##
## 'Positive' Class : 0
##
La regresión logística para el dataset Boston y todas su características clasifica correctamente los valores de si la tasa de criminalidad esta por encima de la media o no, dando un accuracy del 96%
De acuerdo a los resultados obtenidos el error de la predicción es del 3.968254% lo cual es bajo.
LDA
## Call:
## lda(crim_class ~ ., data = training_boston)
##
## Prior probabilities of groups:
## 0 1
## 0.5 0.5
##
## Group means:
## crim zn indus chas nox rm age
## 0 0.09394774 23.3105263 6.534474 0.06315789 0.4684042 6.443968 51.76421
## 1 7.46198268 0.8526316 15.391000 0.07894737 0.6368105 6.089142 86.12842
## dis rad tax ptratio black lstat medv
## 0 5.165645 4.231579 306.5947 17.83105 388.3343 9.226579 25.29579
## 1 2.544885 15.000000 512.4895 19.06737 324.9053 16.366000 19.45105
##
## Coefficients of linear discriminants:
## LD1
## crim 0.003215261
## zn -0.005714802
## indus 0.036000480
## chas -0.027455702
## nox 7.358987150
## rm -0.010280116
## age 0.010946843
## dis 0.047851025
## rad 0.075104765
## tax -0.001610779
## ptratio 0.052141028
## black -0.001032798
## lstat 0.011703725
## medv 0.033793543
Según la función discriminante de LDA, la probabilidad posterior que la tasa de criminalidad sea mayor que la media es del 50%.
De la matriz de confusión
## Confusion Matrix and Statistics
##
## Clase predicha
## Clase real 0 1
## 0 58 5
## 1 12 51
##
## Accuracy : 0.8651
## 95% CI : (0.7928, 0.9194)
## No Information Rate : 0.5556
## P-Value [Acc > NIR] : 8.798e-14
##
## Kappa : 0.7302
##
## Mcnemar's Test P-Value : 0.1456
##
## Sensitivity : 0.8286
## Specificity : 0.9107
## Pos Pred Value : 0.9206
## Neg Pred Value : 0.8095
## Prevalence : 0.5556
## Detection Rate : 0.4603
## Detection Prevalence : 0.5000
## Balanced Accuracy : 0.8696
##
## 'Positive' Class : 0
##
El comportamiento de LDA sobre todas las variables que tiene el dataset Boston decrece con respecto a la regresión logística en las métricas de accuracy, sensibilidad y especificidad.
## [1] "Error de prueba 6.12244897959184 %"
El error se incrementa un poco, sin embargo no es un mal clasificador para todas las variables del dataset.
KNN
## Confusion Matrix and Statistics
##
##
## bosto_knn_predic 0 1
## 0 60 3
## 1 3 60
##
## Accuracy : 0.9524
## 95% CI : (0.8992, 0.9823)
## No Information Rate : 0.5
## P-Value [Acc > NIR] : <2e-16
##
## Kappa : 0.9048
##
## Mcnemar's Test P-Value : 1
##
## Sensitivity : 0.9524
## Specificity : 0.9524
## Pos Pred Value : 0.9524
## Neg Pred Value : 0.9524
## Prevalence : 0.5000
## Detection Rate : 0.4762
## Detection Prevalence : 0.5000
## Balanced Accuracy : 0.9524
##
## 'Positive' Class : 0
##
Se prueba con k = [1,2,3,4,5,6] y se muestran los resultados con k=2 ya que es el k que da mejores resultados, con un accuracy del 95% y una alta tasa de efectividad en ambas clases.
Y un error de prueba, 4.7619048%
Para el dataset completo de Boston, el clasificador que da mejor resultado clasificando si la tasa de criminalidad por ciudad esta por encima o por debajo de la media de Boston, es la regresión logíca.
Sección 8.4. Ejercicios
7. In the lab, we applied random forests to the Boston data using mtry=6 and using ntree=25 and ntree=500. Create a plot displaying the test error resulting from random forests on this data set for a more com- prehensive range of values for mtry and ntree. You can model your plot after Figure 8.10. Describe the results obtained.
Cálculo del número óptimo de variables aleatorias consideradas en cada división de los árboles, para hallar dicho valor, se entrena con 400 árboles
## 1 2 3 4 5 6 7 8 9 10 11 12 13
Cálculo del número óptimo de árboles considerados en el bosque.
A partir de las gráficas anteriores se concluye que los párametros donde se minimiza el error del modelo Random Forest a partir de de los hiperpárametros, número de variables aleatorias consideradas en cada división de los árboles y número de árboles, se tiene que con 7 variables aleatoreas y 20 árboles, aproximadamente, se logra minimizar el error.
8. In the lab, a classification tree was applied to the Carseats data set after converting Sales into a qualitative response variable. Now we will seek to predict Sales using regression trees and related approaches, treating the response as a quantitative variable.
a. Split the data set into a training set and a test set.
Luego de dividir el dataset se tiene
## [1] "Total de datos usados para entrenamiento 301"
## [1] "Total de datos usados para prueba 99"
b. Fit a regression tree to the training set. Plot the tree, and interpret the results. What test MSE do you obtain?
Entrenamiento del árbol y generación de estructura del árbol
La predicción de las ventas de sillas de carros para niños parte de la variable ShelveLoc, esta variable es un factor con niveles malo, bueno y medio que indica la calidad de la ubicación de la estantería para los asientos de automóvil en cada sitio, esta variable es la que mayor pureza tiene y fue la escogida como nodo principal.
Prediciendo a partir de los datos de prueba
## [1] "Error de test (mse) del árbol de regresión tras podado: 5.78"
Este valor es la diferenica entre lo que se estima vs lo que se predice.
c. Use cross-validation in order to determine the optimal level of tree complexity. Does pruning the tree improve the test MSE?
Se busca el ábol que minimiza el error en cross-validation
Gráficamente se evidencia que el error disminuye cuando se tiene árboles de aproximadamente 14 nodos.
## [1] "Error de test (mse) del árbol de regresión tras podado: 5.65"
Luego de realizar el ejercicio de árboles de regresió con cross validation, haciendo pruning con los nodos del árbol, no se ve mejora considerable en el error.
d. Use the bagging approach in order to analyze this data. What test MSE do you obtain? Use the importance() function to determine which variables are most important.
Se entrena y predice con bagging y se tiene un error cuadártico medio para el dataset carseats del 3.1820193
Utilizando bagging para predecir las ventas de dataset carseats, se tiene un error del 3,18%.
Las tres variables más importantes por bagging son Price (Precio que la compañía cobra por los asientos de automóvil en cada sitio), CompPrice (Precio cobrado por el competidor en cada ubicación), Age (Edad promedio de la población local).
## Overall
## Advertising 1.7593765
## Age 2.0755793
## CompPrice 2.1473030
## Education 0.8321542
## Income 1.4218427
## Population 1.3402987
## Price 2.6732834
## ShelveLoc 1.1620987
## Urban 0.1734882
## US 0.2721370
e. Use random forests to analyze this data. What test MSE do you obtain? Use the importance() function to determine which variables are most important. Describe the effect of m, the number of variables considered at each split, on the error rate obtained.
Se entrena el bosque aleatorio
##
## Call:
## randomForest(formula = Sales ~ ., data = training_carseats)
## Type of random forest: regression
## Number of trees: 500
## No. of variables tried at each split: 3
##
## Mean of squared residuals: 2.886273
## % Var explained: 63.59
Y se predice para llegar a la conclusión del MSE
## [1] "Error de test (mse) del modelo obtenido por bagging es: 2.71"
Usando random forest, el error cuádratico medio disminuyó con respecto a los ejercicios anteriores, generando el bagging un MSE del 2.7%.
Con respecto a las variables con mayor importancia en la regresión, se listan las tres más importantes: Age (Edad promedio de la población local), ShelveLoc (Calidad de la ubicación del carro), Price (Precio que la compañía cobra por los asientos de automóvil en cada sitio)
## IncNodePurity
## CompPrice 215.65165
## Income 172.56812
## Advertising 199.15636
## Population 155.29363
## Price 521.67414
## ShelveLoc 601.58022
## Age 253.27218
## Education 85.60067
## Urban 21.00208
## US 25.49282
9. This problem involves the OJ data set which is part of the ISLR package.
El dataset OJ, Orange Juice Data, contiene informació de compras de clientes del producto Citrus Hill o Minute Maid Orange Juice.
a. Create a training set containing a random sample of 800 observations, and a test set containing the remaining observations.
Dividiendo los datos del dataset OJ, se tiene
## [1] "Cantidad de datos para entrenamiento 800"
## [1] "Cantidad de datos para prueba 270"
b. Fit a tree to the training data, with Purchase as the response and the other variables as predictors. Use the summary() function to produce summary statistics about the tree, and describe the results obtained. What is the training error rate? How many terminal nodes does the tree have?
Se entrena el árbol de decisión
##
## Classification tree:
## tree(formula = Purchase ~ ., data = training_oj, split = "deviance")
## Variables actually used in tree construction:
## [1] "LoyalCH" "PriceDiff"
## Number of terminal nodes: 7
## Residual mean deviance: 0.7685 = 609.4 / 793
## Misclassification error rate: 0.1713 = 137 / 800
De acuerdo al resumen del árbol, las variables usadas para la construcción fueron LoyalCH (Fidelización para la marca Country Hill) y PriceDiff (Diferencia de precios entre las dos marcas). Para la cosntrucción del árbol se usaron 7 nodos. La tasa de error del árbol fue del 17%
c. Type in the name of the tree object in order to get a detailed text output. Pick one of the terminal nodes, and interpret the information displayed.
Los caminos que tomo el árbol son descritos a continuación:
## node), split, n, deviance, yval, (yprob)
## * denotes terminal node
##
## 1) root 800 1070.00 CH ( 0.61000 0.39000 )
## 2) LoyalCH < 0.577943 384 475.40 MM ( 0.30990 0.69010 )
## 4) LoyalCH < 0.276142 165 109.50 MM ( 0.10303 0.89697 )
## 8) LoyalCH < 0.0506575 66 10.36 MM ( 0.01515 0.98485 ) *
## 9) LoyalCH > 0.0506575 99 87.58 MM ( 0.16162 0.83838 ) *
## 5) LoyalCH > 0.276142 219 302.60 MM ( 0.46575 0.53425 )
## 10) PriceDiff < 0.05 88 98.97 MM ( 0.25000 0.75000 ) *
## 11) PriceDiff > 0.05 131 175.10 CH ( 0.61069 0.38931 ) *
## 3) LoyalCH > 0.577943 416 293.40 CH ( 0.88702 0.11298 )
## 6) LoyalCH < 0.705699 116 132.60 CH ( 0.74138 0.25862 )
## 12) PriceDiff < 0.31 81 106.80 CH ( 0.62963 0.37037 ) *
## 13) PriceDiff > 0.31 35 0.00 CH ( 1.00000 0.00000 ) *
## 7) LoyalCH > 0.705699 300 130.60 CH ( 0.94333 0.05667 ) *
Si se toma el nodo terminal 7 para análizar, se tiene que cuando loyalCH es mayor a 0.7056, es decir cuando la fidelización de la marca CH este en un 70%, definitivamente el consumidor compra Citrull Hill
d. Create a plot of the tree, and interpret the results.
La clase que más predomina es CH, la variable seleccionada como la principal para dividir el árbol es LoyalCH, las demás variables que fueron tenidas en cuenta en la división del árbol, son PriceDiff, SalesPriceMM, StoreID.
e. Predict the response on the test data, and produce a confusion matrix comparing the test labels to the predicted test labels. What is the test error rate?
## Confusion Matrix and Statistics
##
## arbol_class_predic
## CH MM
## CH 145 20
## MM 36 69
##
## Accuracy : 0.7926
## 95% CI : (0.7393, 0.8394)
## No Information Rate : 0.6704
## P-Value [Acc > NIR] : 6.24e-06
##
## Kappa : 0.5512
##
## Mcnemar's Test P-Value : 0.04502
##
## Sensitivity : 0.8011
## Specificity : 0.7753
## Pos Pred Value : 0.8788
## Neg Pred Value : 0.6571
## Prevalence : 0.6704
## Detection Rate : 0.5370
## Detection Prevalence : 0.6111
## Balanced Accuracy : 0.7882
##
## 'Positive' Class : CH
##
## [1] "Error de prueba 20.7407407407407 %"
El error en la clasificación es del 20%, esta alto. Las clases de acuerdo a la matriz de confusión están bien clasificadas en un 80% y un 77%, si bien estos porcentajes no son bajos son más los valores que no estan siendo bien clasificados.
f. Apply the cv.tree() function to the training set in order to determine the optimal tree size.
set.seed(88)
cv_arbol_purchase <- cv.tree(arbol_class_oj, K = 10)
Se busca el ábol que minimiza el error en cross-validation
g. Produce a plot with tree size on the x-axis and cross-validated classification error rate on the y-axis.
Gráficamente se evidencia que el error disminuye cuando se tiene árboles de 6 nodos, con una desviación 691.6392301
h. Which tree size corresponds to the lowest cross-validated classification error rate?
El tamaño del árbol con menor cross-validated classification error rate es en 6
i. Produce a pruned tree corresponding to the optimal tree size obtained using cross-validation. If cross-validation does not lead to selection of a pruned tree, then create a pruned tree with five terminal nodes.
arbol_pruning_purchase <- prune.tree(tree = arbol_class_oj, best = 5)
arbol_pruning_purchase_predic <- predict(arbol_pruning_purchase, newdata = testing_oj, type = 'class')
j. Compare the training error rates between the pruned and unpruned trees. Which is higher?
Error de entrenamiento del árbol pruned es del 17,13%
##
## Classification tree:
## snip.tree(tree = arbol_class_oj, nodes = c(4L, 6L))
## Variables actually used in tree construction:
## [1] "LoyalCH" "PriceDiff"
## Number of terminal nodes: 5
## Residual mean deviance: 0.8136 = 646.8 / 795
## Misclassification error rate: 0.1713 = 137 / 800
Error entrenamiento del árbol sin pruned es del 15,5%
##
## Classification tree:
## tree(formula = Purchase ~ ., data = training_oj, split = "deviance")
## Variables actually used in tree construction:
## [1] "LoyalCH" "PriceDiff"
## Number of terminal nodes: 7
## Residual mean deviance: 0.7685 = 609.4 / 793
## Misclassification error rate: 0.1713 = 137 / 800
En este caso, para este dataset el árbol sin podar da menor error que el podado.
k. Compare the test error rates between the pruned and unpruned trees. Which is higher?
## [1] "Error de prueba árbol con poda 20.7407407407407 %"
## [1] "Error de prueba sin poda 20.7407407407407 %"
El error de predicción del árbol sin podar y con poda da igual.
10. We now use boosting to predict Salary in the Hitters data set.
Dataset Hitters (Baseball Data) contiene data de la Major League Baseball de los añs comprendidos entre 1896 y 1987
a. Remove the observations for whom the salary information is unknown, and then log-transform the salaries.
## [1] "Número de registros Hitters 322"
## [1] "Número de registros luego de borrar los registros con NA 263"
b. Create a training set consisting of the first 200 observations, and a test set consisting of the remaining observations.
Al crear las particiones, la distribución de los datos queda
## [1] "Cantidad de datos para entrenamiento 200"
## [1] "Cantidad de datos para prueba 63"
c. Perform boosting on the training set with 1,000 trees for a range of values of the shrinkage parameter λ. Produce a plot with different shrinkage values on the x-axis and the corresponding training set MSE on the y-axis.
d. Produce a plot with different shrinkage values on the x-axis and the corresponding test set MSE on the y-axis.
e. Compare the test MSE of boosting to the test MSE that results from applying two of the regression approaches seen in Chapters 3 and 6.
## [1] "MSE Regresión lineal 0.630915057618637"
## [1] "Lasso MSE 0.604826398905786"
Ambos MSE, regresión lineal y Lasso son muy similares, con respecto a los ejercicios anteriores de boosting depende de los hiperpámetros seleccionadas que el error mejora o no con respecto a estas otras técnicas.
f. Which variables appear to be the most important predictors in the boosted model?
## var rel.inf
## CHits CHits 12.7065340
## CAtBat CAtBat 11.4605587
## CRBI CRBI 9.2651413
## CRuns CRuns 9.2535351
## CHmRun CHmRun 7.8977774
## CWalks CWalks 7.1547349
## Years Years 7.1027416
## Walks Walks 5.5662112
## PutOuts PutOuts 4.9388454
## Errors Errors 4.0765635
## Assists Assists 4.0303369
## Hits Hits 3.9379516
## HmRun HmRun 3.4552994
## AtBat AtBat 3.1137945
## Runs Runs 2.6690238
## RBI RBI 2.3916342
## Division Division 0.4293353
## League League 0.3034874
## NewLeague NewLeague 0.2464937
Las variables que aparecen con mayor importancia son CAtBat(Número de veces al bate durante su carrera ),CRBI (Número de carreras bateadas durante su carrera), CHits (Número de hits durante su carrera).
g. Now apply bagging to the training set. What is the test set MSE for this approach?
## [1] "Error cuadrático medio para bagging dataset Hitters es 0.438560919104772 %"
11. This question uses the Caravan data set.
El dataset Caravan - The Insurance Company (TIC) Benchmark - contiene información demográfica de clientes, derivada a partir del zip code. Cada registro contiene 86 variables que indican si un cliente compra la póliza de seguros Caravana.
a. Create a training set consisting of the first 1,000 observations, and a test set consisting of the remaining observations.
Luego de crear las particiones, se distribuyen los datos así
## [1] "Cantidad de datos para entrenamiento 1002"
## [1] "Cantidad de datos para prueba 4820"
b. Fit a boosting model to the training set with Purchase as the response and the other variables as predictors. Use 1,000 trees, and a shrinkage value of 0.01. Which predictors appear to be the most important?
## var rel.inf
## PPERSAUT PPERSAUT 14.365206
## MOPLHOOG MOPLHOOG 9.048732
## MOPLLAAG MOPLLAAG 8.605076
## PBRAND PBRAND 8.275614
## APERSAUT APERSAUT 6.925575
## MINK7512 MINK7512 6.223595
Las 3 características más importantes que explican la variación máxima en el conjunto de datos son PPERSAUT, MOPLHOOG, MINK7512
c. Use the boosting model to predict the response on the test data. Predict that a person will make a purchase if the estimated probability of purchase is greater than 20 %. Form a confusion matrix. What fraction of the people predicted to make a purchase do in fact make one? How does this compare with the results obtained from applying KNN or logistic regression to this data set?
## Clase real
## Clase predicha No Yes
## Yes 4532 288
El 0.059751% de las personas que el modelo predijo que compraban, efectivamente compraron. Cabe mencionar que los resultados estan condicionados a lo indicado por el encabezado del ejercicio, donde se determina que compra cuando la probabilidad es superior al 20%.
12. Apply boosting, bagging, and random forests to a data set of your choice. Be sure to fit the models on a training set and to evaluate their performance on a test set. How accurate are the results compared to simple methods like linear or logistic regression? Which of these approaches yields the best performance?
El dataset a selecccionar para realizar el ejercico es Weekly, el cual contiene información de los mercados en diferentes años. Para este ejercicio las variables con las que se van a predecir son los con los porcentajes de inversión y el volumen.
## Year Lag1 Lag2 Lag3
## Min. :1990 Min. :-18.1950 Min. :-18.1950 Min. :-18.1950
## 1st Qu.:1995 1st Qu.: -1.1540 1st Qu.: -1.1540 1st Qu.: -1.1580
## Median :2000 Median : 0.2410 Median : 0.2410 Median : 0.2410
## Mean :2000 Mean : 0.1506 Mean : 0.1511 Mean : 0.1472
## 3rd Qu.:2005 3rd Qu.: 1.4050 3rd Qu.: 1.4090 3rd Qu.: 1.4090
## Max. :2010 Max. : 12.0260 Max. : 12.0260 Max. : 12.0260
## Lag4 Lag5 Volume
## Min. :-18.1950 Min. :-18.1950 Min. :0.08747
## 1st Qu.: -1.1580 1st Qu.: -1.1660 1st Qu.:0.33202
## Median : 0.2380 Median : 0.2340 Median :1.00268
## Mean : 0.1458 Mean : 0.1399 Mean :1.57462
## 3rd Qu.: 1.4090 3rd Qu.: 1.4050 3rd Qu.:2.05373
## Max. : 12.0260 Max. : 12.0260 Max. :9.32821
## Today Direction Direction_factor
## Min. :-18.1950 Down:484 Down:484
## 1st Qu.: -1.1540 Up :605 Up :605
## Median : 0.2410
## Mean : 0.1499
## 3rd Qu.: 1.4050
## Max. : 12.0260
Se usa los dataset ya creados al inicio de este trabajo, sección 4, para prueba y entrenamiento
## [1] "Tamaño dataset de entremiento 817"
## [1] "Tamaño dataset de prueba 272"
Aproximación desde Regresión logística
## Real
## Predicho Down Up
## 0 15 11
## 1 106 140
## [1] "Error de testing en regresión logística 0.430147058823529 %"
Aproximación desde Boosting
##
## tit_rep_boost 0 1
## 0 66 85
## 1 55 66
## [1] "Error de testing en boosting 0.514705882352941 %"
Aproximación desde Bagging
##
## wee_rep_bagging 0 1
## 0 36 33
## 1 85 118
## [1] "Error de testing en boosting 0.433823529411765 %"
Aproximación desdes Random Forests
##
## wee_rep_rf 0 1
## 0 38 40
## 1 83 111
## [1] "Error de testing en random forest 0.452205882352941 %"
De los cuatro acercamientos de clasificación, regresión logística tiene un error en las pruebas.
9. Sección Aplicación
4. Generate a simulated two-class data set with 100 observations and two features in which there is a visible but non-linear separation between the two classes. Show that in this setting, a support vector machine with a polynomial kernel (with degree greater than 1) or a radial kernel will outperform a support vector classifier on the training data. Which technique performs best on the test data? Make plots and report training and test error rates in order to back up your assertions.
SVM Lineal
Acá se evidencia la separación lineal. En los datos de prueba, 10 observaciones fueron mal clasificadas (x en amarillo)
Matiz de confusión
##
## 0 1
## 0 15 10
## 1 1 24
El modelo lineal tiene 10 errores en los datos de entrenamiento.
SVM Polinomial
Matiz de confusión
##
## 0 1
## 0 15 10
## 1 2 23
El polinomio con grado 3 tiene 15 errores en los datos de entrenamiento.
SVM Radial
Matiz de confusión
##
## 0 1
## 0 25 0
## 1 0 25
Este clasificador clasifica correctamente los datos de entrenamiento
Para los datos de prueba
SVM Lineal
Matiz de confusión
##
## 0 1
## 0 18 7
## 1 0 25
SVM Polinomial
##
## 0 1
## 0 12 13
## 1 4 21
Matiz de confusión
SVM Radial
##
## 0 1
## 0 25 0
## 1 2 23
Matiz de confusión
Kernel radial clasifica correctamente todo el datas set, con cero errores.
5. We have seen that we can fit an SVM with a non-linear kernel in order to perform classification using a non-linear decision boundary. We will now see that we can also obtain a non-linear decision boundary by performing logistic regression using non-linear transformations of the features.
a. Generate a data set with n = 500 and p = 2, such that the observations belong to two classes with a quadratic decision boundary between them.
set.seed(88)
x1 = runif(500) - 0.5
x2 = runif(500) - 0.5
y = 1 * (x1^2 - x2^2 > 0)
b. Plot the observations, colored according to their class labels. Your plot should display X1 on the x-axis, and X2 on the y-axis.
c. Fit a logistic regression model to the data, using X1 and X2 as predictors.
##
## Call:
## glm(formula = y ~ x1 + x2, family = binomial)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.26659 -1.17245 0.00186 1.17609 1.26591
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -0.002219 0.089621 -0.025 0.980
## x1 0.177170 0.311325 0.569 0.569
## x2 0.246780 0.310005 0.796 0.426
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 693.15 on 499 degrees of freedom
## Residual deviance: 692.17 on 497 degrees of freedom
## AIC: 698.17
##
## Number of Fisher Scoring iterations: 3
Acá ninguna variable x1, x2, es estadísticamente significativa.
d. Apply this model to the training data in order to obtain a predicted class label for each training observation. Plot the observations, colored according to the predicted class labels. The decision boundary should be linear.
e. Now fit a logistic regression model to the data using non-linear functions of X1 and X2 as predictors (e.g. X12, X1 ×X2, log(X2), and so forth).
##
## Call:
## glm(formula = y ~ poly(x1, 2) + poly(x2, 2), family = "binomial",
## data = data5)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -0.002452 0.000000 0.000000 0.000000 0.003333
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -42.82 1363.26 -0.031 0.975
## poly(x1, 2)1 -3293.43 60263.57 -0.055 0.956
## poly(x1, 2)2 89538.58 1284724.45 0.070 0.944
## poly(x2, 2)1 1987.54 48690.31 0.041 0.967
## poly(x2, 2)2 -87431.32 1253356.74 -0.070 0.944
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 6.9315e+02 on 499 degrees of freedom
## Residual deviance: 2.3301e-05 on 495 degrees of freedom
## AIC: 10
##
## Number of Fisher Scoring iterations: 25
f. Apply this model to the training data in order to obtain a predicted class label for each training observation. Plot the observations, colored according to the predicted class labels. The decision boundary should be obviously non-linear. If it is not, then repeat (a)-(e) until you come up with an example in which the predicted class labels are obviously non-linear.
g. Fit a support vector classifier to the data with X1 and X2 as predictors. Obtain a class prediction for each training observation. Plot the observations, colored according to the predicted class labels.
h. Fit a SVM using a non-linear kernel to the data. Obtain a class prediction for each training observation. Plot the observations, colored according to the predicted class labels.
i. Comment on your results.
Los SVM con kernel no lineal son extremadamente poderosos para encontrar límites no lineales
6. At the end of Section 9.6.1, it is claimed that in the case of data that is just barely linearly separable, a support vector classifier with a small value of cost that misclassifies a couple of training observations may perform better on test data than one with a huge value of cost that does not misclassify any training observations. You will now investigate this claim.
a. Generate two-class data with p = 2 in such a way that the classes are just barely linearly separable.
b. Compute the cross-validation error rates for support vector classifiers with a range of cost values. How many training errors are misclassified for each value of cost considered, and how does this relate to the cross-validation errors obtained?
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 10000
##
## - best performance: 0
##
## - Detailed performance results:
## cost error dispersion
## 1 1e-02 0.05909091 0.02752409
## 2 1e-01 0.04545455 0.02606765
## 3 1e+00 0.04636364 0.02551580
## 4 5e+00 0.04636364 0.02551580
## 5 1e+01 0.04727273 0.02599710
## 6 1e+02 0.04727273 0.02599710
## 7 1e+03 0.03454545 0.03779992
## 8 1e+04 0.00000000 0.00000000
La tabla de asociación de los costos con sus errores de clasificación, muestra que cuando el costo es igual a 10000 tiene un error de 0, es decir, clasifica todo los puntos correctamente.
## cost misclass
## 1 1e-02 65
## 2 1e-01 50
## 3 1e+00 51
## 4 5e+00 51
## 5 1e+01 52
## 6 1e+02 52
## 7 1e+03 38
## 8 1e+04 0
c. Generate an appropriate test data set, and compute the test errors corresponding to each of the values of cost considered. Which value of cost leads to the fewest test errors, and how does this compare to the values of cost that yield the fewest training errors and the fewest cross-validation errors?
Se generan datos de prueba aleatoriamente
## cost test.misclass
## 1 1e-02 63
## 2 1e-01 20
## 3 1e+00 2
## 4 5e+00 0
## 5 1e+01 1
## 6 1e+02 169
## 7 1e+03 189
## 8 1e+04 189
El costo igual a 10 parece tener mejor desempeño en la data de prueba.
d. Discuss your results.
Los costos pequeños tiene buen desempeño en los modelos de SVM, por lo visto en estos datos.
7. In this problem, you will use support vector approaches in order to predict whether a given car gets high or low gas mileage based on the Auto data set.
a. Create a binary variable that takes on a 1 for cars with gas mileage above the median, and a 0 for cars with gas mileage below the median.
auto_df <- Auto
mpg_median <- median(auto_df$mpg)
auto_df$mpg01 <- ifelse(auto_df$mpg >= mpg_median, 1, 0)
b. Fit a support vector classifier to the data with various values of cost, in order to predict whether a car gets high or low gas mileage. Report the cross-validation errors associated with different values of this parameter. Comment on your results.
## [1] 130
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 130
##
## - best performance: 0.06534729
##
## - Detailed performance results:
## cost error dispersion
## 1 0.001 0.50543440 0.05582610
## 2 0.010 0.41217431 0.04771583
## 3 0.100 0.09901973 0.03136295
## 4 1.000 0.08186904 0.03890945
## 5 5.000 0.07791657 0.04345538
## 6 10.000 0.07639944 0.04465616
## 7 100.000 0.06616937 0.02976093
## 8 130.000 0.06534729 0.02528966
El parárametro costo define que cantidad de puntos usa el modelo para seleccionar un vector de soporte, es el parámetro de penalización del término de error. Controla la compensación entre el límite de decisión suave y la clasificación correcta de los puntos de entrenamiento.
Al costo ser más grande, selecciona más y puede caer en sobreajuste. Para este caso, el mejor parárametro de costo basado en los posibles valores a probar es 130, donde se tiene un error del 3%, sin embargo pensando en que entre más grande el valor más se ajustan los datos, se podría tomar un valor costo de 10 y no se sacrifica tanto error, porque sería del 4%.
c. Now repeat (b), this time using SVMs with radial and polynomial basis kernels, with different values of gamma and degree and cost. Comment on your results.
## [1] "Mejor Kernel: "
## [1] "Mejor Cost: 10"
## [1] "Mejor Gamma: 0.1"
## [1] "Mejor Degree: 1"
## $best.parameters
## degree gamma cost
## 157 1 0.1 10
##
## $best.performance
## [1] 0.03870228
##
## $method
## [1] "svm"
##
## $nparcomb
## [1] 240
##
## $train.ind
## $train.ind$`(0.609,40.1]`
## [1] 291 220 335 218 316 327 157 250 106 137 276 119 130 71 287 80 163
## [18] 1 104 52 248 182 39 326 12 329 260 307 367 246 9 112 270 330
## [35] 172 341 261 125 290 256 381 109 138 359 292 378 123 66 70 212 151
## [52] 334 239 159 347 336 16 31 143 179 181 202 226 370 210 17 128 168
## [69] 337 363 255 175 59 184 38 26 373 214 222 332 288 213 238 234 29
## [86] 355 369 333 94 87 199 124 133 93 140 129 81 36 249 65 389 126
## [103] 186 303 352 219 383 110 22 388 301 308 131 148 86 174 198 344 183
## [120] 282 387 385 47 92 141 73 142 54 46 379 310 277 160 154 3 103
## [137] 167 295 254 166 262 266 368 147 278 132 233 194 114 169 75 6 8
## [154] 259 20 164 221 56 165 120 244 97 64 225 5 348 105 189 242 108
## [171] 349 285 45 69 312 362 211 350 377 18 68 364 302 95 345 139 72
## [188] 206 34 13 229 197 4 102 360 224 156 371 78 134 187 171 88 328
## [205] 33 60 99 57 269 343 200 313 306 376 41 191 146 243 192 155 76
## [222] 11 96 382 136 79 207 67 50 55 299 281 204 158 245 384 322 232
## [239] 2 331 283 353 25 297 193 51 152 176 263 231 304 386 82 314 272
## [256] 338 296 188 325 273 40 223 275 236 340 235 311 91 24 185 85 170
## [273] 365 215 375 346 30 127 149 217 117 216 23 32 294 116 74 63 98
## [290] 121 7 58 323 380 150 252 351 144 62 19 49 205 251 14 153 203
## [307] 10 228 358 35 309 286 90 230 100 305 53 43 107 77 339 42 178
## [324] 357 253 84 265 289 271 173 317 21 361 177 227 391 392 162 196 372
## [341] 27 366 190 113 274 257 264 390 83 37 321 61
##
## $train.ind$`(40.1,79.2]`
## [1] 135 280 115 201 268 89 318 258 354 145 15 195 267 48 241 324 356
## [18] 284 28 111 161 342 122 320 315 247 300 180 237 118 44 298 208 240
## [35] 209 279 374 101 319 293 256 381 109 138 359 292 378 123 66 70 212
## [52] 151 334 239 159 347 336 16 31 143 179 181 202 226 370 210 17 128
## [69] 168 337 363 255 175 59 184 38 26 373 214 222 332 288 213 238 234
## [86] 29 355 369 333 94 87 199 124 133 93 140 129 81 36 249 65 389
## [103] 126 186 303 352 219 383 110 22 388 301 308 131 148 86 174 198 344
## [120] 183 282 387 385 47 92 141 73 142 54 46 379 310 277 160 154 3
## [137] 103 167 295 254 166 262 266 368 147 278 132 233 194 114 169 75 6
## [154] 8 259 20 164 221 56 165 120 244 97 64 225 5 348 105 189 242
## [171] 108 349 285 45 69 312 362 211 350 377 18 68 364 302 95 345 139
## [188] 72 206 34 13 229 197 4 102 360 224 156 371 78 134 187 171 88
## [205] 328 33 60 99 57 269 343 200 313 306 376 41 191 146 243 192 155
## [222] 76 11 96 382 136 79 207 67 50 55 299 281 204 158 245 384 322
## [239] 232 2 331 283 353 25 297 193 51 152 176 263 231 304 386 82 314
## [256] 272 338 296 188 325 273 40 223 275 236 340 235 311 91 24 185 85
## [273] 170 365 215 375 346 30 127 149 217 117 216 23 32 294 116 74 63
## [290] 98 121 7 58 323 380 150 252 351 144 62 19 49 205 251 14 153
## [307] 203 10 228 358 35 309 286 90 230 100 305 53 43 107 77 339 42
## [324] 178 357 253 84 265 289 271 173 317 21 361 177 227 391 392 162 196
## [341] 372 27 366 190 113 274 257 264 390 83 37 321 61
##
## $train.ind$`(79.2,118]`
## [1] 135 280 115 201 268 89 318 258 354 145 15 195 267 48 241 324 356
## [18] 284 28 111 161 342 122 320 315 247 300 180 237 118 44 298 208 240
## [35] 209 279 374 101 319 293 291 220 335 218 316 327 157 250 106 137 276
## [52] 119 130 71 287 80 163 1 104 52 248 182 39 326 12 329 260 307
## [69] 367 246 9 112 270 330 172 341 261 125 290 222 332 288 213 238 234
## [86] 29 355 369 333 94 87 199 124 133 93 140 129 81 36 249 65 389
## [103] 126 186 303 352 219 383 110 22 388 301 308 131 148 86 174 198 344
## [120] 183 282 387 385 47 92 141 73 142 54 46 379 310 277 160 154 3
## [137] 103 167 295 254 166 262 266 368 147 278 132 233 194 114 169 75 6
## [154] 8 259 20 164 221 56 165 120 244 97 64 225 5 348 105 189 242
## [171] 108 349 285 45 69 312 362 211 350 377 18 68 364 302 95 345 139
## [188] 72 206 34 13 229 197 4 102 360 224 156 371 78 134 187 171 88
## [205] 328 33 60 99 57 269 343 200 313 306 376 41 191 146 243 192 155
## [222] 76 11 96 382 136 79 207 67 50 55 299 281 204 158 245 384 322
## [239] 232 2 331 283 353 25 297 193 51 152 176 263 231 304 386 82 314
## [256] 272 338 296 188 325 273 40 223 275 236 340 235 311 91 24 185 85
## [273] 170 365 215 375 346 30 127 149 217 117 216 23 32 294 116 74 63
## [290] 98 121 7 58 323 380 150 252 351 144 62 19 49 205 251 14 153
## [307] 203 10 228 358 35 309 286 90 230 100 305 53 43 107 77 339 42
## [324] 178 357 253 84 265 289 271 173 317 21 361 177 227 391 392 162 196
## [341] 372 27 366 190 113 274 257 264 390 83 37 321 61
##
## $train.ind$`(118,157]`
## [1] 135 280 115 201 268 89 318 258 354 145 15 195 267 48 241 324 356
## [18] 284 28 111 161 342 122 320 315 247 300 180 237 118 44 298 208 240
## [35] 209 279 374 101 319 293 291 220 335 218 316 327 157 250 106 137 276
## [52] 119 130 71 287 80 163 1 104 52 248 182 39 326 12 329 260 307
## [69] 367 246 9 112 270 330 172 341 261 125 290 256 381 109 138 359 292
## [86] 378 123 66 70 212 151 334 239 159 347 336 16 31 143 179 181 202
## [103] 226 370 210 17 128 168 337 363 255 175 59 184 38 26 373 214 344
## [120] 183 282 387 385 47 92 141 73 142 54 46 379 310 277 160 154 3
## [137] 103 167 295 254 166 262 266 368 147 278 132 233 194 114 169 75 6
## [154] 8 259 20 164 221 56 165 120 244 97 64 225 5 348 105 189 242
## [171] 108 349 285 45 69 312 362 211 350 377 18 68 364 302 95 345 139
## [188] 72 206 34 13 229 197 4 102 360 224 156 371 78 134 187 171 88
## [205] 328 33 60 99 57 269 343 200 313 306 376 41 191 146 243 192 155
## [222] 76 11 96 382 136 79 207 67 50 55 299 281 204 158 245 384 322
## [239] 232 2 331 283 353 25 297 193 51 152 176 263 231 304 386 82 314
## [256] 272 338 296 188 325 273 40 223 275 236 340 235 311 91 24 185 85
## [273] 170 365 215 375 346 30 127 149 217 117 216 23 32 294 116 74 63
## [290] 98 121 7 58 323 380 150 252 351 144 62 19 49 205 251 14 153
## [307] 203 10 228 358 35 309 286 90 230 100 305 53 43 107 77 339 42
## [324] 178 357 253 84 265 289 271 173 317 21 361 177 227 391 392 162 196
## [341] 372 27 366 190 113 274 257 264 390 83 37 321 61
##
## $train.ind$`(157,196]`
## [1] 135 280 115 201 268 89 318 258 354 145 15 195 267 48 241 324 356
## [18] 284 28 111 161 342 122 320 315 247 300 180 237 118 44 298 208 240
## [35] 209 279 374 101 319 293 291 220 335 218 316 327 157 250 106 137 276
## [52] 119 130 71 287 80 163 1 104 52 248 182 39 326 12 329 260 307
## [69] 367 246 9 112 270 330 172 341 261 125 290 256 381 109 138 359 292
## [86] 378 123 66 70 212 151 334 239 159 347 336 16 31 143 179 181 202
## [103] 226 370 210 17 128 168 337 363 255 175 59 184 38 26 373 214 222
## [120] 332 288 213 238 234 29 355 369 333 94 87 199 124 133 93 140 129
## [137] 81 36 249 65 389 126 186 303 352 219 383 110 22 388 301 308 131
## [154] 148 86 174 198 221 56 165 120 244 97 64 225 5 348 105 189 242
## [171] 108 349 285 45 69 312 362 211 350 377 18 68 364 302 95 345 139
## [188] 72 206 34 13 229 197 4 102 360 224 156 371 78 134 187 171 88
## [205] 328 33 60 99 57 269 343 200 313 306 376 41 191 146 243 192 155
## [222] 76 11 96 382 136 79 207 67 50 55 299 281 204 158 245 384 322
## [239] 232 2 331 283 353 25 297 193 51 152 176 263 231 304 386 82 314
## [256] 272 338 296 188 325 273 40 223 275 236 340 235 311 91 24 185 85
## [273] 170 365 215 375 346 30 127 149 217 117 216 23 32 294 116 74 63
## [290] 98 121 7 58 323 380 150 252 351 144 62 19 49 205 251 14 153
## [307] 203 10 228 358 35 309 286 90 230 100 305 53 43 107 77 339 42
## [324] 178 357 253 84 265 289 271 173 317 21 361 177 227 391 392 162 196
## [341] 372 27 366 190 113 274 257 264 390 83 37 321 61
##
## $train.ind$`(196,236]`
## [1] 135 280 115 201 268 89 318 258 354 145 15 195 267 48 241 324 356
## [18] 284 28 111 161 342 122 320 315 247 300 180 237 118 44 298 208 240
## [35] 209 279 374 101 319 293 291 220 335 218 316 327 157 250 106 137 276
## [52] 119 130 71 287 80 163 1 104 52 248 182 39 326 12 329 260 307
## [69] 367 246 9 112 270 330 172 341 261 125 290 256 381 109 138 359 292
## [86] 378 123 66 70 212 151 334 239 159 347 336 16 31 143 179 181 202
## [103] 226 370 210 17 128 168 337 363 255 175 59 184 38 26 373 214 222
## [120] 332 288 213 238 234 29 355 369 333 94 87 199 124 133 93 140 129
## [137] 81 36 249 65 389 126 186 303 352 219 383 110 22 388 301 308 131
## [154] 148 86 174 198 344 183 282 387 385 47 92 141 73 142 54 46 379
## [171] 310 277 160 154 3 103 167 295 254 166 262 266 368 147 278 132 233
## [188] 194 114 169 75 6 8 259 20 164 224 156 371 78 134 187 171 88
## [205] 328 33 60 99 57 269 343 200 313 306 376 41 191 146 243 192 155
## [222] 76 11 96 382 136 79 207 67 50 55 299 281 204 158 245 384 322
## [239] 232 2 331 283 353 25 297 193 51 152 176 263 231 304 386 82 314
## [256] 272 338 296 188 325 273 40 223 275 236 340 235 311 91 24 185 85
## [273] 170 365 215 375 346 30 127 149 217 117 216 23 32 294 116 74 63
## [290] 98 121 7 58 323 380 150 252 351 144 62 19 49 205 251 14 153
## [307] 203 10 228 358 35 309 286 90 230 100 305 53 43 107 77 339 42
## [324] 178 357 253 84 265 289 271 173 317 21 361 177 227 391 392 162 196
## [341] 372 27 366 190 113 274 257 264 390 83 37 321 61
##
## $train.ind$`(236,275]`
## [1] 135 280 115 201 268 89 318 258 354 145 15 195 267 48 241 324 356
## [18] 284 28 111 161 342 122 320 315 247 300 180 237 118 44 298 208 240
## [35] 209 279 374 101 319 293 291 220 335 218 316 327 157 250 106 137 276
## [52] 119 130 71 287 80 163 1 104 52 248 182 39 326 12 329 260 307
## [69] 367 246 9 112 270 330 172 341 261 125 290 256 381 109 138 359 292
## [86] 378 123 66 70 212 151 334 239 159 347 336 16 31 143 179 181 202
## [103] 226 370 210 17 128 168 337 363 255 175 59 184 38 26 373 214 222
## [120] 332 288 213 238 234 29 355 369 333 94 87 199 124 133 93 140 129
## [137] 81 36 249 65 389 126 186 303 352 219 383 110 22 388 301 308 131
## [154] 148 86 174 198 344 183 282 387 385 47 92 141 73 142 54 46 379
## [171] 310 277 160 154 3 103 167 295 254 166 262 266 368 147 278 132 233
## [188] 194 114 169 75 6 8 259 20 164 221 56 165 120 244 97 64 225
## [205] 5 348 105 189 242 108 349 285 45 69 312 362 211 350 377 18 68
## [222] 364 302 95 345 139 72 206 34 13 229 197 4 102 360 245 384 322
## [239] 232 2 331 283 353 25 297 193 51 152 176 263 231 304 386 82 314
## [256] 272 338 296 188 325 273 40 223 275 236 340 235 311 91 24 185 85
## [273] 170 365 215 375 346 30 127 149 217 117 216 23 32 294 116 74 63
## [290] 98 121 7 58 323 380 150 252 351 144 62 19 49 205 251 14 153
## [307] 203 10 228 358 35 309 286 90 230 100 305 53 43 107 77 339 42
## [324] 178 357 253 84 265 289 271 173 317 21 361 177 227 391 392 162 196
## [341] 372 27 366 190 113 274 257 264 390 83 37 321 61
##
## $train.ind$`(275,314]`
## [1] 135 280 115 201 268 89 318 258 354 145 15 195 267 48 241 324 356
## [18] 284 28 111 161 342 122 320 315 247 300 180 237 118 44 298 208 240
## [35] 209 279 374 101 319 293 291 220 335 218 316 327 157 250 106 137 276
## [52] 119 130 71 287 80 163 1 104 52 248 182 39 326 12 329 260 307
## [69] 367 246 9 112 270 330 172 341 261 125 290 256 381 109 138 359 292
## [86] 378 123 66 70 212 151 334 239 159 347 336 16 31 143 179 181 202
## [103] 226 370 210 17 128 168 337 363 255 175 59 184 38 26 373 214 222
## [120] 332 288 213 238 234 29 355 369 333 94 87 199 124 133 93 140 129
## [137] 81 36 249 65 389 126 186 303 352 219 383 110 22 388 301 308 131
## [154] 148 86 174 198 344 183 282 387 385 47 92 141 73 142 54 46 379
## [171] 310 277 160 154 3 103 167 295 254 166 262 266 368 147 278 132 233
## [188] 194 114 169 75 6 8 259 20 164 221 56 165 120 244 97 64 225
## [205] 5 348 105 189 242 108 349 285 45 69 312 362 211 350 377 18 68
## [222] 364 302 95 345 139 72 206 34 13 229 197 4 102 360 224 156 371
## [239] 78 134 187 171 88 328 33 60 99 57 269 343 200 313 306 376 41
## [256] 191 146 243 192 155 76 11 96 382 136 79 207 67 50 55 299 281
## [273] 204 158 215 375 346 30 127 149 217 117 216 23 32 294 116 74 63
## [290] 98 121 7 58 323 380 150 252 351 144 62 19 49 205 251 14 153
## [307] 203 10 228 358 35 309 286 90 230 100 305 53 43 107 77 339 42
## [324] 178 357 253 84 265 289 271 173 317 21 361 177 227 391 392 162 196
## [341] 372 27 366 190 113 274 257 264 390 83 37 321 61
##
## $train.ind$`(314,353]`
## [1] 135 280 115 201 268 89 318 258 354 145 15 195 267 48 241 324 356
## [18] 284 28 111 161 342 122 320 315 247 300 180 237 118 44 298 208 240
## [35] 209 279 374 101 319 293 291 220 335 218 316 327 157 250 106 137 276
## [52] 119 130 71 287 80 163 1 104 52 248 182 39 326 12 329 260 307
## [69] 367 246 9 112 270 330 172 341 261 125 290 256 381 109 138 359 292
## [86] 378 123 66 70 212 151 334 239 159 347 336 16 31 143 179 181 202
## [103] 226 370 210 17 128 168 337 363 255 175 59 184 38 26 373 214 222
## [120] 332 288 213 238 234 29 355 369 333 94 87 199 124 133 93 140 129
## [137] 81 36 249 65 389 126 186 303 352 219 383 110 22 388 301 308 131
## [154] 148 86 174 198 344 183 282 387 385 47 92 141 73 142 54 46 379
## [171] 310 277 160 154 3 103 167 295 254 166 262 266 368 147 278 132 233
## [188] 194 114 169 75 6 8 259 20 164 221 56 165 120 244 97 64 225
## [205] 5 348 105 189 242 108 349 285 45 69 312 362 211 350 377 18 68
## [222] 364 302 95 345 139 72 206 34 13 229 197 4 102 360 224 156 371
## [239] 78 134 187 171 88 328 33 60 99 57 269 343 200 313 306 376 41
## [256] 191 146 243 192 155 76 11 96 382 136 79 207 67 50 55 299 281
## [273] 204 158 245 384 322 232 2 331 283 353 25 297 193 51 152 176 263
## [290] 231 304 386 82 314 272 338 296 188 325 273 40 223 275 236 340 235
## [307] 311 91 24 185 85 170 365 90 230 100 305 53 43 107 77 339 42
## [324] 178 357 253 84 265 289 271 173 317 21 361 177 227 391 392 162 196
## [341] 372 27 366 190 113 274 257 264 390 83 37 321 61
##
## $train.ind$`(353,392]`
## [1] 135 280 115 201 268 89 318 258 354 145 15 195 267 48 241 324 356
## [18] 284 28 111 161 342 122 320 315 247 300 180 237 118 44 298 208 240
## [35] 209 279 374 101 319 293 291 220 335 218 316 327 157 250 106 137 276
## [52] 119 130 71 287 80 163 1 104 52 248 182 39 326 12 329 260 307
## [69] 367 246 9 112 270 330 172 341 261 125 290 256 381 109 138 359 292
## [86] 378 123 66 70 212 151 334 239 159 347 336 16 31 143 179 181 202
## [103] 226 370 210 17 128 168 337 363 255 175 59 184 38 26 373 214 222
## [120] 332 288 213 238 234 29 355 369 333 94 87 199 124 133 93 140 129
## [137] 81 36 249 65 389 126 186 303 352 219 383 110 22 388 301 308 131
## [154] 148 86 174 198 344 183 282 387 385 47 92 141 73 142 54 46 379
## [171] 310 277 160 154 3 103 167 295 254 166 262 266 368 147 278 132 233
## [188] 194 114 169 75 6 8 259 20 164 221 56 165 120 244 97 64 225
## [205] 5 348 105 189 242 108 349 285 45 69 312 362 211 350 377 18 68
## [222] 364 302 95 345 139 72 206 34 13 229 197 4 102 360 224 156 371
## [239] 78 134 187 171 88 328 33 60 99 57 269 343 200 313 306 376 41
## [256] 191 146 243 192 155 76 11 96 382 136 79 207 67 50 55 299 281
## [273] 204 158 245 384 322 232 2 331 283 353 25 297 193 51 152 176 263
## [290] 231 304 386 82 314 272 338 296 188 325 273 40 223 275 236 340 235
## [307] 311 91 24 185 85 170 365 215 375 346 30 127 149 217 117 216 23
## [324] 32 294 116 74 63 98 121 7 58 323 380 150 252 351 144 62 19
## [341] 49 205 251 14 153 203 10 228 358 35 309 286
##
##
## $sampling
## [1] "10-fold cross validation"
Al igual que el parámetro cost, gamma cuando toma valores muy altos tiende a sobreajustar el modelo, en este caso el gamma óptimo de los posibles dados para realizar el tunning es un gamma bajo (0.01) al igual que el costo. Gamma es usado en hiperplanos no lineales. Ambos parámetros controlan la variance y el bias (parcialidad) de los SMV.
Por su parte degree son los grados del polinomio usado para encontrar el hiperplano que divide los datos, solo se tiene en cuenta cuando se usa este tipo de función, en este ejercicio al mostar valor óptimo en el parámetro degree igual a 1 indica que se utilzó como función de kernel el valor lineal.
d. Make some plots to back up your assertions in (b) and (c). Hint: In the lab, we used the plot() function for svm objects only in cases with p = 2. When p > 2, you can use the plot() function to create plots displaying pairs of variables at a time. Essentially, instead of typing plot(svmfit , dat) where svmfit contains your fitted model and dat is a data frame containing your data, you can type plot(svmfit , dat , x1∼x4) in order to plot just the first and fourth variables. However, you must replace x1 and x4 with the correct variable names. To find out more, type ?plot.svm.
8. This problem involves the OJ data set which is part of the ISLR package.
a Create a training set containing a random sample of 800 observations, and a test set containing the remaining observations.
Actividad realizada en el capítulo 8.4 Clasificación, sección 9, ejercicio a
## [1] "Cantidad de datos para entrenamiento dataset OJ 800"
## [1] "Cantidad de datos para prueba dataset OJ 270"
b. Fit a support vector classifier to the training data using cost=0.01, with Purchase as the response and the other variables as predictors. Use the summary() function to produce summary statistics, and describe the results obtained.
##
## Call:
## svm(formula = Purchase ~ ., data = training_oj, cost = 0.01)
##
##
## Parameters:
## SVM-Type: C-classification
## SVM-Kernel: radial
## cost: 0.01
##
## Number of Support Vectors: 626
##
## ( 314 312 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
Las máquinas de soporte vectorial para el dataset OJ, prediciendo si un cliente compra Citrus Hill o Minute Maid Orange Juice indica que son dos clases las que utilizó, las cuales tienen los niveles o toman los valores de CH y MM, construyó 626 vectores de soporte de los cuales 314 fueron para CH y 312 para MM.
c. What are the training and test error rates?
Error de entrenamiento
## Confusion Matrix and Statistics
##
## real
## predicho CH MM
## CH 488 312
## MM 0 0
##
## Accuracy : 0.61
## 95% CI : (0.5752, 0.644)
## No Information Rate : 0.61
## P-Value [Acc > NIR] : 0.5155
##
## Kappa : 0
##
## Mcnemar's Test P-Value : <2e-16
##
## Sensitivity : 1.00
## Specificity : 0.00
## Pos Pred Value : 0.61
## Neg Pred Value : NaN
## Prevalence : 0.61
## Detection Rate : 0.61
## Detection Prevalence : 1.00
## Balanced Accuracy : 0.50
##
## 'Positive' Class : CH
##
A partir de la matriz de confusión, el error de entrenamiento es del 0.39%
## Confusion Matrix and Statistics
##
## real
## predicho CH MM
## CH 165 105
## MM 0 0
##
## Accuracy : 0.6111
## 95% CI : (0.5501, 0.6696)
## No Information Rate : 0.6111
## P-Value [Acc > NIR] : 0.5267
##
## Kappa : 0
##
## Mcnemar's Test P-Value : <2e-16
##
## Sensitivity : 1.0000
## Specificity : 0.0000
## Pos Pred Value : 0.6111
## Neg Pred Value : NaN
## Prevalence : 0.6111
## Detection Rate : 0.6111
## Detection Prevalence : 1.0000
## Balanced Accuracy : 0.5000
##
## 'Positive' Class : CH
##
A partir de la matriz de confusión, el error de entrenamiento es del 0.3888889%
d. Use the tune() function to select an optimal cost. Consider values in the range 0.01 to 10.
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 0.005
##
## - best performance: 0.165
##
## - Detailed performance results:
## cost error dispersion
## 1 0.005 0.16500 0.03809710
## 2 0.010 0.17250 0.03899786
## 3 0.015 0.17375 0.03839216
## 4 0.020 0.16875 0.03644345
## 5 0.025 0.16875 0.04050463
## 6 0.030 0.17000 0.04005205
## 7 0.035 0.17000 0.04005205
## 8 0.040 0.17250 0.04281744
## 9 0.045 0.17750 0.04518481
## 10 0.050 0.17125 0.03955042
## 11 0.055 0.17125 0.04084609
## 12 0.060 0.17250 0.04116363
## 13 0.065 0.17125 0.03998698
## 14 0.070 0.17250 0.03525699
## 15 0.075 0.17375 0.03458584
## 16 0.080 0.17375 0.03458584
## 17 0.085 0.17375 0.03458584
## 18 0.090 0.17250 0.03622844
## 19 0.095 0.17125 0.03729108
## 20 0.100 0.17125 0.03729108
## 21 0.105 0.17125 0.03729108
## 22 0.110 0.17125 0.03729108
## 23 0.115 0.17250 0.03899786
## 24 0.120 0.17250 0.03899786
## 25 0.125 0.17250 0.03899786
## 26 0.130 0.17250 0.03899786
## 27 0.135 0.17250 0.03899786
## 28 0.140 0.17125 0.03729108
## 29 0.145 0.17125 0.03729108
## 30 0.150 0.17250 0.03622844
## 31 0.155 0.17375 0.03793727
## 32 0.160 0.17250 0.03763863
## 33 0.165 0.17375 0.03928617
## 34 0.170 0.17375 0.03928617
## 35 0.175 0.17375 0.03928617
## 36 0.180 0.17375 0.03928617
## 37 0.185 0.17375 0.03928617
## 38 0.190 0.17375 0.03928617
## 39 0.195 0.17375 0.03928617
## 40 0.200 0.17375 0.03793727
## 41 0.205 0.17375 0.03793727
## 42 0.210 0.17250 0.03763863
## 43 0.215 0.17250 0.03763863
## 44 0.220 0.17250 0.03763863
## 45 0.225 0.17250 0.03763863
## 46 0.230 0.17250 0.03763863
## 47 0.235 0.17250 0.03763863
## 48 0.240 0.17250 0.03763863
## 49 0.245 0.17250 0.03763863
## 50 0.250 0.17250 0.03763863
## 51 0.255 0.17250 0.03763863
## 52 0.260 0.17250 0.03763863
## 53 0.265 0.17250 0.03763863
## 54 0.270 0.17250 0.03763863
## 55 0.275 0.17250 0.03763863
## 56 0.280 0.17250 0.03763863
## 57 0.285 0.17250 0.03763863
## 58 0.290 0.17250 0.03763863
## 59 0.295 0.17250 0.03763863
## 60 0.300 0.17250 0.03763863
## 61 0.305 0.17250 0.03763863
## 62 0.310 0.17250 0.03763863
## 63 0.315 0.17250 0.03763863
## 64 0.320 0.17250 0.03763863
## 65 0.325 0.17250 0.03763863
## 66 0.330 0.17250 0.03763863
## 67 0.335 0.17250 0.03763863
## 68 0.340 0.17250 0.03763863
## 69 0.345 0.17125 0.03955042
## 70 0.350 0.17125 0.03955042
## 71 0.355 0.17250 0.03899786
## 72 0.360 0.17250 0.03899786
## 73 0.365 0.17125 0.03955042
## 74 0.370 0.17125 0.03955042
## 75 0.375 0.17125 0.03955042
## 76 0.380 0.17250 0.03763863
## 77 0.385 0.17375 0.03557562
## 78 0.390 0.17375 0.03557562
## 79 0.395 0.17375 0.03557562
## 80 0.400 0.17375 0.03557562
## 81 0.405 0.17375 0.03557562
## 82 0.410 0.17375 0.03557562
## 83 0.415 0.17375 0.03557562
## 84 0.420 0.17375 0.03557562
## 85 0.425 0.17375 0.03557562
## 86 0.430 0.17375 0.03557562
## 87 0.435 0.17375 0.03557562
## 88 0.440 0.17375 0.03557562
## 89 0.445 0.17375 0.03557562
## 90 0.450 0.17375 0.03557562
## 91 0.455 0.17375 0.03557562
## 92 0.460 0.17375 0.03557562
## 93 0.465 0.17375 0.03557562
## 94 0.470 0.17375 0.03557562
## 95 0.475 0.17375 0.03557562
## 96 0.480 0.17375 0.03557562
## 97 0.485 0.17375 0.03557562
## 98 0.490 0.17375 0.03557562
## 99 0.495 0.17375 0.03557562
## 100 0.500 0.17375 0.03557562
## 101 0.505 0.17375 0.03557562
## 102 0.510 0.17375 0.03557562
## 103 0.515 0.17375 0.03557562
## 104 0.520 0.17375 0.03557562
## 105 0.525 0.17375 0.03557562
## 106 0.530 0.17375 0.03557562
## 107 0.535 0.17375 0.03557562
## 108 0.540 0.17375 0.03557562
## 109 0.545 0.17375 0.03557562
## 110 0.550 0.17375 0.03557562
## 111 0.555 0.17375 0.03557562
## 112 0.560 0.17375 0.03557562
## 113 0.565 0.17375 0.03557562
## 114 0.570 0.17500 0.03584302
## 115 0.575 0.17500 0.03584302
## 116 0.580 0.17500 0.03584302
## 117 0.585 0.17500 0.03584302
## 118 0.590 0.17500 0.03584302
## 119 0.595 0.17500 0.03584302
## 120 0.600 0.17500 0.03584302
## 121 0.605 0.17500 0.03584302
## 122 0.610 0.17500 0.03584302
## 123 0.615 0.17500 0.03584302
## 124 0.620 0.17500 0.03584302
## 125 0.625 0.17500 0.03584302
## 126 0.630 0.17500 0.03584302
## 127 0.635 0.17500 0.03584302
## 128 0.640 0.17500 0.03584302
## 129 0.645 0.17500 0.03584302
## 130 0.650 0.17500 0.03584302
## 131 0.655 0.17500 0.03584302
## 132 0.660 0.17500 0.03584302
## 133 0.665 0.17500 0.03584302
## 134 0.670 0.17500 0.03584302
## 135 0.675 0.17500 0.03584302
## 136 0.680 0.17500 0.03584302
## 137 0.685 0.17500 0.03584302
## 138 0.690 0.17500 0.03584302
## 139 0.695 0.17500 0.03584302
## 140 0.700 0.17500 0.03584302
## 141 0.705 0.17625 0.03557562
## 142 0.710 0.17625 0.03557562
## 143 0.715 0.17625 0.03557562
## 144 0.720 0.17625 0.03557562
## 145 0.725 0.17625 0.03557562
## 146 0.730 0.17625 0.03557562
## 147 0.735 0.17625 0.03557562
## 148 0.740 0.17625 0.03557562
## 149 0.745 0.17625 0.03557562
## 150 0.750 0.17625 0.03557562
## 151 0.755 0.17625 0.03557562
## 152 0.760 0.17625 0.03557562
## 153 0.765 0.17625 0.03557562
## 154 0.770 0.17625 0.03557562
## 155 0.775 0.17625 0.03557562
## 156 0.780 0.17625 0.03557562
## 157 0.785 0.17625 0.03557562
## 158 0.790 0.17625 0.03557562
## 159 0.795 0.17625 0.03557562
## 160 0.800 0.17625 0.03557562
## 161 0.805 0.17625 0.03557562
## 162 0.810 0.17625 0.03557562
## 163 0.815 0.17625 0.03557562
## 164 0.820 0.17625 0.03557562
## 165 0.825 0.17625 0.03557562
## 166 0.830 0.17625 0.03557562
## 167 0.835 0.17625 0.03557562
## 168 0.840 0.17625 0.03557562
## 169 0.845 0.17625 0.03557562
## 170 0.850 0.17625 0.03557562
## 171 0.855 0.17750 0.03476109
## 172 0.860 0.17625 0.03557562
## 173 0.865 0.17625 0.03557562
## 174 0.870 0.17750 0.03476109
## 175 0.875 0.17750 0.03476109
## 176 0.880 0.17750 0.03476109
## 177 0.885 0.17750 0.03476109
## 178 0.890 0.17750 0.03476109
## 179 0.895 0.17750 0.03476109
## 180 0.900 0.17750 0.03476109
## 181 0.905 0.17750 0.03476109
## 182 0.910 0.17750 0.03476109
## 183 0.915 0.17750 0.03476109
## 184 0.920 0.17750 0.03476109
## 185 0.925 0.17750 0.03476109
## 186 0.930 0.17750 0.03476109
## 187 0.935 0.17750 0.03476109
## 188 0.940 0.17750 0.03476109
## 189 0.945 0.17750 0.03476109
## 190 0.950 0.17750 0.03476109
## 191 0.955 0.17750 0.03476109
## 192 0.960 0.17750 0.03476109
## 193 0.965 0.17750 0.03476109
## 194 0.970 0.17750 0.03476109
## 195 0.975 0.17750 0.03476109
## 196 0.980 0.17750 0.03476109
## 197 0.985 0.17750 0.03476109
## 198 0.990 0.17750 0.03476109
## 199 0.995 0.17750 0.03476109
## 200 1.000 0.17750 0.03476109
El costo óptimo es de 0.2
e Compute the training and test error rates using this new value for cost.
Matriz de confusión de entrenamiento
confusionMatrix(cm_train)
## Confusion Matrix and Statistics
##
##
## CH MM
## CH 488 312
## MM 0 0
##
## Accuracy : 0.61
## 95% CI : (0.5752, 0.644)
## No Information Rate : 0.61
## P-Value [Acc > NIR] : 0.5155
##
## Kappa : 0
##
## Mcnemar's Test P-Value : <2e-16
##
## Sensitivity : 1.00
## Specificity : 0.00
## Pos Pred Value : 0.61
## Neg Pred Value : NaN
## Prevalence : 0.61
## Detection Rate : 0.61
## Detection Prevalence : 1.00
## Balanced Accuracy : 0.50
##
## 'Positive' Class : CH
##
Matriz de confusión de prueba
confusionMatrix(cm_test)
## Confusion Matrix and Statistics
##
##
## oj_svmpred_aftertun CH MM
## CH 165 105
## MM 0 0
##
## Accuracy : 0.6111
## 95% CI : (0.5501, 0.6696)
## No Information Rate : 0.6111
## P-Value [Acc > NIR] : 0.5267
##
## Kappa : 0
##
## Mcnemar's Test P-Value : <2e-16
##
## Sensitivity : 1.0000
## Specificity : 0.0000
## Pos Pred Value : 0.6111
## Neg Pred Value : NaN
## Prevalence : 0.6111
## Detection Rate : 0.6111
## Detection Prevalence : 1.0000
## Balanced Accuracy : 0.5000
##
## 'Positive' Class : CH
##
## [1] "Error de entrenamiento: 0.39 %"
## [1] "Error de prueba: 0.388888888888889 %"
Para este conjunto de datos luego de aplicar el valor de costo dado en el ejercicio anterior, se tiene que los errores de entrenamiento y prueba disminuyen considerablemente con respecto al punto c.
f. Repeat parts (b) through (e) using a support vector machine with a radial kernel. Use the default value for gamma.
##
## Call:
## svm(formula = Purchase ~ ., data = training_oj, kernel = "radial")
##
##
## Parameters:
## SVM-Type: C-classification
## SVM-Kernel: radial
## cost: 1
##
## Number of Support Vectors: 377
##
## ( 190 187 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
Construyó 377 vectores de soporte de los cuales 191 fueron para CH y 186 para MM.
Error de entrenamiento
## Confusion Matrix and Statistics
##
## real
## predicho CH MM
## CH 449 78
## MM 39 234
##
## Accuracy : 0.8538
## 95% CI : (0.8273, 0.8775)
## No Information Rate : 0.61
## P-Value [Acc > NIR] : < 2.2e-16
##
## Kappa : 0.6855
##
## Mcnemar's Test P-Value : 0.0004429
##
## Sensitivity : 0.9201
## Specificity : 0.7500
## Pos Pred Value : 0.8520
## Neg Pred Value : 0.8571
## Prevalence : 0.6100
## Detection Rate : 0.5613
## Detection Prevalence : 0.6587
## Balanced Accuracy : 0.8350
##
## 'Positive' Class : CH
##
## [1] "A partir de la matriz de confusión, el error de entrenamiento es del 0.14625 %"
## Confusion Matrix and Statistics
##
## real
## predicho CH MM
## CH 151 27
## MM 14 78
##
## Accuracy : 0.8481
## 95% CI : (0.7997, 0.8888)
## No Information Rate : 0.6111
## P-Value [Acc > NIR] : < 2e-16
##
## Kappa : 0.6732
##
## Mcnemar's Test P-Value : 0.06092
##
## Sensitivity : 0.9152
## Specificity : 0.7429
## Pos Pred Value : 0.8483
## Neg Pred Value : 0.8478
## Prevalence : 0.6111
## Detection Rate : 0.5593
## Detection Prevalence : 0.6593
## Balanced Accuracy : 0.8290
##
## 'Positive' Class : CH
##
## [1] "A partir de la matriz de confusión, el error de predicción es del 0.151851851851852 %"
Hipertuning del costo (c)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 0.845
##
## - best performance: 0.16375
##
## - Detailed performance results:
## cost error dispersion
## 1 0.005 0.39000 0.07041543
## 2 0.010 0.39000 0.07041543
## 3 0.015 0.39000 0.07041543
## 4 0.020 0.39000 0.07041543
## 5 0.025 0.38875 0.07203635
## 6 0.030 0.38250 0.07710022
## 7 0.035 0.30875 0.08478936
## 8 0.040 0.26125 0.06358776
## 9 0.045 0.22625 0.06678375
## 10 0.050 0.20625 0.05504102
## 11 0.055 0.20500 0.05719120
## 12 0.060 0.20250 0.05583955
## 13 0.065 0.19500 0.05439056
## 14 0.070 0.18875 0.05541823
## 15 0.075 0.19000 0.04958158
## 16 0.080 0.18875 0.05152197
## 17 0.085 0.18500 0.05027701
## 18 0.090 0.18500 0.04669642
## 19 0.095 0.18250 0.04830459
## 20 0.100 0.18125 0.04832256
## 21 0.105 0.18125 0.04832256
## 22 0.110 0.18500 0.04706674
## 23 0.115 0.18375 0.04489571
## 24 0.120 0.18125 0.04573854
## 25 0.125 0.18250 0.04417453
## 26 0.130 0.18125 0.04340139
## 27 0.135 0.18250 0.04456581
## 28 0.140 0.18250 0.04377975
## 29 0.145 0.18125 0.04177070
## 30 0.150 0.18375 0.03998698
## 31 0.155 0.18250 0.04174992
## 32 0.160 0.18250 0.04005205
## 33 0.165 0.18250 0.04005205
## 34 0.170 0.18250 0.04005205
## 35 0.175 0.18125 0.04458528
## 36 0.180 0.18000 0.04417453
## 37 0.185 0.17875 0.04411554
## 38 0.190 0.17875 0.04411554
## 39 0.195 0.17750 0.04594683
## 40 0.200 0.17375 0.04730589
## 41 0.205 0.17375 0.04730589
## 42 0.210 0.17375 0.04730589
## 43 0.215 0.17375 0.04730589
## 44 0.220 0.17375 0.04730589
## 45 0.225 0.17500 0.04526159
## 46 0.230 0.17500 0.04526159
## 47 0.235 0.17375 0.04267529
## 48 0.240 0.17375 0.04267529
## 49 0.245 0.17500 0.04448783
## 50 0.250 0.17375 0.04466309
## 51 0.255 0.17375 0.04466309
## 52 0.260 0.17250 0.04632314
## 53 0.265 0.17125 0.04678927
## 54 0.270 0.17250 0.04632314
## 55 0.275 0.17375 0.04730589
## 56 0.280 0.17375 0.04730589
## 57 0.285 0.17375 0.04730589
## 58 0.290 0.17375 0.04730589
## 59 0.295 0.17375 0.04730589
## 60 0.300 0.17375 0.04730589
## 61 0.305 0.17375 0.04730589
## 62 0.310 0.17500 0.04564355
## 63 0.315 0.17625 0.04581439
## 64 0.320 0.17625 0.04581439
## 65 0.325 0.17500 0.04409586
## 66 0.330 0.17500 0.04409586
## 67 0.335 0.17375 0.04581439
## 68 0.340 0.17375 0.04581439
## 69 0.345 0.17500 0.04526159
## 70 0.350 0.17375 0.04767147
## 71 0.355 0.17375 0.04767147
## 72 0.360 0.17375 0.04767147
## 73 0.365 0.17375 0.04767147
## 74 0.370 0.17375 0.04767147
## 75 0.375 0.17375 0.04767147
## 76 0.380 0.17250 0.04632314
## 77 0.385 0.17250 0.04632314
## 78 0.390 0.17250 0.04632314
## 79 0.395 0.17250 0.04632314
## 80 0.400 0.17375 0.04693746
## 81 0.405 0.17375 0.04693746
## 82 0.410 0.17625 0.04466309
## 83 0.415 0.17625 0.04466309
## 84 0.420 0.17375 0.04185375
## 85 0.425 0.17500 0.04289846
## 86 0.430 0.17500 0.04289846
## 87 0.435 0.17500 0.04289846
## 88 0.440 0.17500 0.04289846
## 89 0.445 0.17625 0.04143687
## 90 0.450 0.17500 0.04448783
## 91 0.455 0.17375 0.04348132
## 92 0.460 0.17250 0.04199868
## 93 0.465 0.17250 0.04199868
## 94 0.470 0.17250 0.04199868
## 95 0.475 0.17250 0.04199868
## 96 0.480 0.17250 0.04199868
## 97 0.485 0.17250 0.04199868
## 98 0.490 0.17250 0.04199868
## 99 0.495 0.17250 0.04199868
## 100 0.500 0.17250 0.04199868
## 101 0.505 0.17250 0.04199868
## 102 0.510 0.17375 0.04226652
## 103 0.515 0.17250 0.04158325
## 104 0.520 0.17250 0.04158325
## 105 0.525 0.17125 0.04168749
## 106 0.530 0.17125 0.04168749
## 107 0.535 0.17125 0.04168749
## 108 0.540 0.17000 0.04216370
## 109 0.545 0.17000 0.04216370
## 110 0.550 0.17000 0.04216370
## 111 0.555 0.17000 0.04216370
## 112 0.560 0.17000 0.04216370
## 113 0.565 0.17000 0.04216370
## 114 0.570 0.17000 0.04216370
## 115 0.575 0.17000 0.04216370
## 116 0.580 0.17000 0.04216370
## 117 0.585 0.17000 0.04216370
## 118 0.590 0.17000 0.04216370
## 119 0.595 0.17000 0.04216370
## 120 0.600 0.17000 0.04216370
## 121 0.605 0.17000 0.04216370
## 122 0.610 0.17000 0.04216370
## 123 0.615 0.17000 0.04216370
## 124 0.620 0.17000 0.04216370
## 125 0.625 0.17000 0.04216370
## 126 0.630 0.17000 0.04216370
## 127 0.635 0.17000 0.04216370
## 128 0.640 0.17000 0.04216370
## 129 0.645 0.16875 0.04177070
## 130 0.650 0.16875 0.04177070
## 131 0.655 0.16875 0.04177070
## 132 0.660 0.16875 0.04177070
## 133 0.665 0.16875 0.04177070
## 134 0.670 0.16875 0.04177070
## 135 0.675 0.16750 0.04174992
## 136 0.680 0.16750 0.04174992
## 137 0.685 0.16750 0.04174992
## 138 0.690 0.16750 0.04174992
## 139 0.695 0.16750 0.04174992
## 140 0.700 0.16750 0.04174992
## 141 0.705 0.16750 0.04174992
## 142 0.710 0.16750 0.04174992
## 143 0.715 0.16750 0.04174992
## 144 0.720 0.16625 0.04084609
## 145 0.725 0.16500 0.04116363
## 146 0.730 0.16500 0.04116363
## 147 0.735 0.16500 0.04116363
## 148 0.740 0.16500 0.04116363
## 149 0.745 0.16500 0.04116363
## 150 0.750 0.16750 0.04005205
## 151 0.755 0.16750 0.04005205
## 152 0.760 0.16750 0.04005205
## 153 0.765 0.16625 0.04041881
## 154 0.770 0.16625 0.04041881
## 155 0.775 0.16625 0.04041881
## 156 0.780 0.16625 0.04041881
## 157 0.785 0.16625 0.04041881
## 158 0.790 0.16625 0.04041881
## 159 0.795 0.16625 0.04041881
## 160 0.800 0.16625 0.04041881
## 161 0.805 0.16500 0.04241004
## 162 0.810 0.16500 0.04241004
## 163 0.815 0.16500 0.04241004
## 164 0.820 0.16500 0.03899786
## 165 0.825 0.16500 0.03899786
## 166 0.830 0.16500 0.03899786
## 167 0.835 0.16500 0.03899786
## 168 0.840 0.16500 0.03899786
## 169 0.845 0.16375 0.03928617
## 170 0.850 0.16375 0.03928617
## 171 0.855 0.16375 0.03928617
## 172 0.860 0.16375 0.03928617
## 173 0.865 0.16375 0.03928617
## 174 0.870 0.16375 0.03928617
## 175 0.875 0.16500 0.03670453
## 176 0.880 0.16500 0.03670453
## 177 0.885 0.16500 0.03670453
## 178 0.890 0.16500 0.03670453
## 179 0.895 0.16500 0.03670453
## 180 0.900 0.16500 0.03670453
## 181 0.905 0.16500 0.03670453
## 182 0.910 0.16500 0.03670453
## 183 0.915 0.16500 0.03670453
## 184 0.920 0.16500 0.03670453
## 185 0.925 0.16500 0.03670453
## 186 0.930 0.16500 0.03670453
## 187 0.935 0.16500 0.03670453
## 188 0.940 0.16500 0.03670453
## 189 0.945 0.16500 0.03670453
## 190 0.950 0.16500 0.03670453
## 191 0.955 0.16500 0.03670453
## 192 0.960 0.16500 0.03670453
## 193 0.965 0.16500 0.03670453
## 194 0.970 0.16500 0.03670453
## 195 0.975 0.16500 0.03670453
## 196 0.980 0.16500 0.03670453
## 197 0.985 0.16500 0.03670453
## 198 0.990 0.16500 0.03670453
## 199 0.995 0.16500 0.03670453
## 200 1.000 0.16500 0.03670453
El costo óptimo para el kernel radial es de 0.52
Cálculo del error en entrenamiento y pruebas luego de aplicar el parámetro óptimo de C
## Confusion Matrix and Statistics
##
##
## CH MM
## CH 449 77
## MM 39 235
##
## Accuracy : 0.855
## 95% CI : (0.8287, 0.8787)
## No Information Rate : 0.61
## P-Value [Acc > NIR] : < 2.2e-16
##
## Kappa : 0.6884
##
## Mcnemar's Test P-Value : 0.0005918
##
## Sensitivity : 0.9201
## Specificity : 0.7532
## Pos Pred Value : 0.8536
## Neg Pred Value : 0.8577
## Prevalence : 0.6100
## Detection Rate : 0.5613
## Detection Prevalence : 0.6575
## Balanced Accuracy : 0.8366
##
## 'Positive' Class : CH
##
## [1] "Error con datos de entrenamiento: 0.145 %"
## Confusion Matrix and Statistics
##
##
## oj_svmpred_kernel_aftertun CH MM
## CH 151 27
## MM 14 78
##
## Accuracy : 0.8481
## 95% CI : (0.7997, 0.8888)
## No Information Rate : 0.6111
## P-Value [Acc > NIR] : < 2e-16
##
## Kappa : 0.6732
##
## Mcnemar's Test P-Value : 0.06092
##
## Sensitivity : 0.9152
## Specificity : 0.7429
## Pos Pred Value : 0.8483
## Neg Pred Value : 0.8478
## Prevalence : 0.6111
## Detection Rate : 0.5593
## Detection Prevalence : 0.6593
## Balanced Accuracy : 0.8290
##
## 'Positive' Class : CH
##
## [1] "Error con datos de prueba: 0.151851851851852 %"
Acá los errores de entrenamiento y pruebas son muy similares y así como en el ejercicio (f), son iguales luego de hacer hipertunning.
g. Repeat parts (b) through (e) using a support vector machine with a polynomial kernel. Set degree=2.
##
## Call:
## svm(formula = Purchase ~ ., data = training_oj, kernel = "polynomial",
## degree = 2)
##
##
## Parameters:
## SVM-Type: C-classification
## SVM-Kernel: polynomial
## cost: 1
## degree: 2
## coef.0: 0
##
## Number of Support Vectors: 460
##
## ( 232 228 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
Construyó 460 vectores de soporte de los cuales 223 fueron para CH y 228 para MM. Uso el valor de costo por defecto (1)
## Confusion Matrix and Statistics
##
## real
## predicho CH MM
## CH 452 113
## MM 36 199
##
## Accuracy : 0.8138
## 95% CI : (0.785, 0.8402)
## No Information Rate : 0.61
## P-Value [Acc > NIR] : < 2.2e-16
##
## Kappa : 0.5903
##
## Mcnemar's Test P-Value : 4.78e-10
##
## Sensitivity : 0.9262
## Specificity : 0.6378
## Pos Pred Value : 0.8000
## Neg Pred Value : 0.8468
## Prevalence : 0.6100
## Detection Rate : 0.5650
## Detection Prevalence : 0.7063
## Balanced Accuracy : 0.7820
##
## 'Positive' Class : CH
##
## [1] "Error de entrenamiento: 0.18625 %"
## Confusion Matrix and Statistics
##
## real
## predicho CH MM
## CH 153 38
## MM 12 67
##
## Accuracy : 0.8148
## 95% CI : (0.7633, 0.8593)
## No Information Rate : 0.6111
## P-Value [Acc > NIR] : 4.049e-13
##
## Kappa : 0.592
##
## Mcnemar's Test P-Value : 0.000407
##
## Sensitivity : 0.9273
## Specificity : 0.6381
## Pos Pred Value : 0.8010
## Neg Pred Value : 0.8481
## Prevalence : 0.6111
## Detection Rate : 0.5667
## Detection Prevalence : 0.7074
## Balanced Accuracy : 0.7827
##
## 'Positive' Class : CH
##
## [1] "A partir de la matriz de confusón, el error de prueba es del: 0.185185185185185 %"
Hipertuning del costo (C)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 0.64
##
## - best performance: 0.195
##
## - Detailed performance results:
## cost error dispersion
## 1 0.005 0.37250 0.07236098
## 2 0.010 0.37125 0.06615691
## 3 0.015 0.37125 0.06615691
## 4 0.020 0.36250 0.05432669
## 5 0.025 0.35000 0.06236096
## 6 0.030 0.34125 0.06375136
## 7 0.035 0.33250 0.06851602
## 8 0.040 0.33000 0.06513874
## 9 0.045 0.32625 0.06883202
## 10 0.050 0.32375 0.06573569
## 11 0.055 0.32125 0.06948471
## 12 0.060 0.32000 0.07269609
## 13 0.065 0.32000 0.07100469
## 14 0.070 0.31625 0.07072295
## 15 0.075 0.31500 0.06790516
## 16 0.080 0.31625 0.06822400
## 17 0.085 0.31375 0.06958458
## 18 0.090 0.30875 0.06948471
## 19 0.095 0.30125 0.06730166
## 20 0.100 0.29750 0.06230525
## 21 0.105 0.29250 0.06723714
## 22 0.110 0.28625 0.06857933
## 23 0.115 0.28125 0.07246886
## 24 0.120 0.28000 0.07364517
## 25 0.125 0.28125 0.07246886
## 26 0.130 0.27250 0.07472171
## 27 0.135 0.27000 0.07504628
## 28 0.140 0.26500 0.07331439
## 29 0.145 0.26125 0.06857933
## 30 0.150 0.25875 0.06667969
## 31 0.155 0.25625 0.06647107
## 32 0.160 0.25500 0.06697844
## 33 0.165 0.25000 0.06614378
## 34 0.170 0.24750 0.06449591
## 35 0.175 0.24375 0.06434769
## 36 0.180 0.24750 0.06258328
## 37 0.185 0.24500 0.06379220
## 38 0.190 0.24125 0.06209592
## 39 0.195 0.23875 0.06303934
## 40 0.200 0.23500 0.06739189
## 41 0.205 0.23500 0.06739189
## 42 0.210 0.23250 0.06671873
## 43 0.215 0.23125 0.06568284
## 44 0.220 0.23125 0.06568284
## 45 0.225 0.22875 0.06615691
## 46 0.230 0.22750 0.06529846
## 47 0.235 0.22625 0.06108112
## 48 0.240 0.22000 0.06297045
## 49 0.245 0.21875 0.06407732
## 50 0.250 0.21500 0.05974483
## 51 0.255 0.21500 0.05974483
## 52 0.260 0.21375 0.05905800
## 53 0.265 0.21125 0.06050999
## 54 0.270 0.20750 0.06185781
## 55 0.275 0.20750 0.06101002
## 56 0.280 0.20625 0.06298424
## 57 0.285 0.20625 0.06298424
## 58 0.290 0.20625 0.06298424
## 59 0.295 0.20750 0.06101002
## 60 0.300 0.20750 0.06101002
## 61 0.305 0.20750 0.06101002
## 62 0.310 0.20875 0.06237487
## 63 0.315 0.21000 0.06061032
## 64 0.320 0.20875 0.05894029
## 65 0.325 0.20750 0.05749396
## 66 0.330 0.20750 0.05749396
## 67 0.335 0.20750 0.05749396
## 68 0.340 0.20625 0.05870418
## 69 0.345 0.20500 0.05719120
## 70 0.350 0.20500 0.05719120
## 71 0.355 0.20500 0.05719120
## 72 0.360 0.20375 0.05714565
## 73 0.365 0.20375 0.05434266
## 74 0.370 0.20375 0.05434266
## 75 0.375 0.20375 0.05434266
## 76 0.380 0.20375 0.05434266
## 77 0.385 0.20375 0.05434266
## 78 0.390 0.20375 0.05434266
## 79 0.395 0.20375 0.05434266
## 80 0.400 0.20375 0.05434266
## 81 0.405 0.20250 0.05296750
## 82 0.410 0.20125 0.05415064
## 83 0.415 0.20125 0.05415064
## 84 0.420 0.20250 0.05583955
## 85 0.425 0.20250 0.05916080
## 86 0.430 0.20250 0.05916080
## 87 0.435 0.20250 0.05916080
## 88 0.440 0.20125 0.05787019
## 89 0.445 0.20125 0.05787019
## 90 0.450 0.20000 0.06009252
## 91 0.455 0.20000 0.06009252
## 92 0.460 0.20000 0.06009252
## 93 0.465 0.20000 0.06009252
## 94 0.470 0.20000 0.06009252
## 95 0.475 0.19875 0.05993341
## 96 0.480 0.19875 0.05993341
## 97 0.485 0.20000 0.06180165
## 98 0.490 0.20000 0.06180165
## 99 0.495 0.20000 0.06180165
## 100 0.500 0.20000 0.06180165
## 101 0.505 0.19875 0.06079622
## 102 0.510 0.19875 0.06079622
## 103 0.515 0.19625 0.06010696
## 104 0.520 0.19625 0.06010696
## 105 0.525 0.19625 0.06010696
## 106 0.530 0.19750 0.06032320
## 107 0.535 0.19750 0.06032320
## 108 0.540 0.19750 0.06032320
## 109 0.545 0.19750 0.06032320
## 110 0.550 0.19750 0.06032320
## 111 0.555 0.19750 0.06202598
## 112 0.560 0.19750 0.06202598
## 113 0.565 0.19750 0.06202598
## 114 0.570 0.19750 0.06202598
## 115 0.575 0.19750 0.06202598
## 116 0.580 0.19750 0.06202598
## 117 0.585 0.19750 0.06202598
## 118 0.590 0.19750 0.06202598
## 119 0.595 0.19625 0.06347845
## 120 0.600 0.19625 0.06347845
## 121 0.605 0.19625 0.06347845
## 122 0.610 0.19625 0.06347845
## 123 0.615 0.19625 0.06347845
## 124 0.620 0.19625 0.06347845
## 125 0.625 0.19625 0.06347845
## 126 0.630 0.19625 0.06347845
## 127 0.635 0.19625 0.06347845
## 128 0.640 0.19500 0.06213784
## 129 0.645 0.19625 0.06320436
## 130 0.650 0.19625 0.06320436
## 131 0.655 0.19625 0.06320436
## 132 0.660 0.19625 0.06320436
## 133 0.665 0.19625 0.06320436
## 134 0.670 0.19625 0.06320436
## 135 0.675 0.19750 0.06529846
## 136 0.680 0.19750 0.06529846
## 137 0.685 0.19750 0.06529846
## 138 0.690 0.19750 0.06529846
## 139 0.695 0.19750 0.06529846
## 140 0.700 0.19750 0.06529846
## 141 0.705 0.19750 0.06529846
## 142 0.710 0.19750 0.06529846
## 143 0.715 0.19750 0.06529846
## 144 0.720 0.19875 0.06386020
## 145 0.725 0.19875 0.06386020
## 146 0.730 0.19875 0.06386020
## 147 0.735 0.19875 0.06386020
## 148 0.740 0.19875 0.06386020
## 149 0.745 0.19875 0.06386020
## 150 0.750 0.19875 0.06386020
## 151 0.755 0.19875 0.06386020
## 152 0.760 0.19875 0.06386020
## 153 0.765 0.19875 0.06386020
## 154 0.770 0.19875 0.06386020
## 155 0.775 0.19875 0.06386020
## 156 0.780 0.20000 0.06400955
## 157 0.785 0.20000 0.06400955
## 158 0.790 0.20000 0.06400955
## 159 0.795 0.19875 0.06303934
## 160 0.800 0.19875 0.06303934
## 161 0.805 0.19875 0.06303934
## 162 0.810 0.19875 0.06303934
## 163 0.815 0.19875 0.06303934
## 164 0.820 0.20000 0.06428020
## 165 0.825 0.20000 0.06428020
## 166 0.830 0.20000 0.06428020
## 167 0.835 0.20000 0.06428020
## 168 0.840 0.20000 0.06428020
## 169 0.845 0.20000 0.06428020
## 170 0.850 0.20000 0.06428020
## 171 0.855 0.20000 0.06428020
## 172 0.860 0.20000 0.06428020
## 173 0.865 0.20000 0.06428020
## 174 0.870 0.20000 0.06428020
## 175 0.875 0.20000 0.06346478
## 176 0.880 0.20000 0.06346478
## 177 0.885 0.20000 0.06346478
## 178 0.890 0.20000 0.06346478
## 179 0.895 0.19875 0.06220765
## 180 0.900 0.19875 0.06220765
## 181 0.905 0.20125 0.06358776
## 182 0.910 0.20250 0.06449591
## 183 0.915 0.20125 0.06599926
## 184 0.920 0.20125 0.06599926
## 185 0.925 0.20125 0.06599926
## 186 0.930 0.20125 0.06599926
## 187 0.935 0.20125 0.06599926
## 188 0.940 0.20125 0.06599926
## 189 0.945 0.20125 0.06599926
## 190 0.950 0.20125 0.06599926
## 191 0.955 0.20250 0.06449591
## 192 0.960 0.20250 0.06449591
## 193 0.965 0.20250 0.06449591
## 194 0.970 0.20250 0.06449591
## 195 0.975 0.20250 0.06449591
## 196 0.980 0.20250 0.06449591
## 197 0.985 0.20250 0.06449591
## 198 0.990 0.20250 0.06449591
## 199 0.995 0.20250 0.06449591
## 200 1.000 0.20250 0.06449591
El costo óptimo para el kernel radial es de 0.85
Cálculo del error en entrenamiento y pruebas luego de aplicar el parámetro óptimo de C
## Confusion Matrix and Statistics
##
##
## CH MM
## CH 452 119
## MM 36 193
##
## Accuracy : 0.8062
## 95% CI : (0.7771, 0.8331)
## No Information Rate : 0.61
## P-Value [Acc > NIR] : < 2.2e-16
##
## Kappa : 0.5723
##
## Mcnemar's Test P-Value : 4.506e-11
##
## Sensitivity : 0.9262
## Specificity : 0.6186
## Pos Pred Value : 0.7916
## Neg Pred Value : 0.8428
## Prevalence : 0.6100
## Detection Rate : 0.5650
## Detection Prevalence : 0.7137
## Balanced Accuracy : 0.7724
##
## 'Positive' Class : CH
##
## [1] "Error de entrenamiento: 0.19375 %"
## Confusion Matrix and Statistics
##
##
## oj_svmpred_kernel_aftertun CH MM
## CH 154 41
## MM 11 64
##
## Accuracy : 0.8074
## 95% CI : (0.7552, 0.8527)
## No Information Rate : 0.6111
## P-Value [Acc > NIR] : 3.059e-12
##
## Kappa : 0.5726
##
## Mcnemar's Test P-Value : 5.781e-05
##
## Sensitivity : 0.9333
## Specificity : 0.6095
## Pos Pred Value : 0.7897
## Neg Pred Value : 0.8533
## Prevalence : 0.6111
## Detection Rate : 0.5704
## Detection Prevalence : 0.7222
## Balanced Accuracy : 0.7714
##
## 'Positive' Class : CH
##
## [1] "Error de prueba: 0.192592592592593 %"
Ambos errores de entrenamiento y de test dan igual al 18%
h. Overall, which approach seems to give the best results on this data?
Luego de ejecutar 6 diferentes acercamientos a SMV con variació en sus hiperpárametros se encuentra que el modelo donde se disminuyó má los errores de entrenamiento y prueba fue utilizando el kernel radial. Compo conclusión general del ejercicio, en la medida que se pruebe con diferentes parámetros se minimiza en la mayoría de los casos los errores tanto en entrenamiento como en prueba.
Cuando se habla de estado de alerta por que los contaminantes que afectan la calidad del aire se encuentran en los niveles más altos y afectan la salud de los habitantes de los municipios del Área Metropolitana del Valle del Aburrá, el primera culpable al que se dirigen todas las miradas es a los vehículos particulares como principal generador de material particulado PM2.5 y otros contaminantes. Los vehículos particulares son el medio de transporte utilizado por las personas para desplazarse a sus lugares de trabajo, su estudio o para realizar otras actividades que no se encuentran cercanas entre sí, siendo el desplazamiento laboral el mayor y más frecuente factor de movilización.
Si bien en Medellín contamos con un amplio sistema de transporte público, no todas las personas los usan, bien sea porque en el sector donde viven el sistema de transporte público no es el mejor o porque con la cantidad de habitantes del área metropolitana usándolo el sistema sería demasiado congestionado, entre otras posibles opciones para no usarlo. Pero si pensáramos un poco en que medidas podemos incentivar para que las personas no vean la necesidad de desplazarse tan frecuentemente y así minimizar el número de vehículos en las calles, el teletrabajo es una muy buena medidas, tanto para los empleadores como para los empleados, esta comprobado que las personas que trabajan desde sus casas son más productivos, mejoran su calidad de vida e incentivan el trabajo en equipo, las empresas que lo hacen promueven la inclusión social, reducen costos fijos, impulsa el uso apropiado de las tecnologías y lo más importante ambos aportan al mejoramiento de la movilidad en las ciudades y reduce los índices de contaminación [1].
Las técnicas de aprendizaje estadísticos aportan a la consecución del teletrabajo y por ende a contribuir en la solución del problema de calidad del aire en Medellín. A partir de dichas técnicas y con el análisis de la información recopilada en los diferentes sistemas de información de tránsito de la ciudad se puede determinar los días de mayor afluencia de vehículos y generar un sistema de recomendación de días de teletrabajo para los trabajadores, de acuerdo a la ubicación de su hogar, el lugar donde labora y las rutas de acceso más frecuentes, adicionalmente con las técnicas de aprendizaje estadístico, también se puede contribuir a las empresas a seleccionar a las personas que pueden realizar teletrabajo, para nadie es un secreto que aún las empresas no confían 100% en el teletrabajo y no saben cómo seleccionar a los empleados candidatos para hacerlo, es aquí donde dichas técnicas pueden contribuir, implementando un sistema de clasificación en donde a partir de variables demográficas, de desempeño, de funciones laborales y de distancias se pueda determinar que tan viable es para un colaborador llevar a cabo sus labores por fuera de las instalaciones de las empresas. La calidad del aire en los municipios que conforman el área metropolitana depende de las acciones que cada uno de sus habitantes, entes gubernamentales e industria realicen, con miras a mitigar el impacto de nuestras actuaciones en el medio ambiente, es aquí donde a través del teletrabajo cada individuo y empresa pueden contribuir, apoyándose en las técnicas de aprendizaje estadístico, implementando métodos como los expuesto anteriormente y permitiéndose vivir el cambio apoyado de la tecnología, los datos y las técnicas de machine learning.[1] Los cinco beneficios del Teletrabajo que todo empresario debe saber. [Página Web]. Recuperado de https://teletrabajo.gov.co/622/w3-article-11180.html
[2] Gareth James, Daniela Witten, Trevor Hastie Robert Tibshirani. (2013). An Introduction To Statistical Learning. Springer. pp 168, pp 332, pp 368